Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    PHP




Delete Array Element


How can i delete an element from one array. Let us suppose that i've an array of 10 elements $a[0], $a[1], $a[2]...etc
And when i delete $a[2] i wanna the elements to be re-ordered like this
$a[0] will be the same $a[0]
$a[1] will be the same $a[1]
but $a[2] will be the $a[3] element i had before deleting $a[2]

It would be called in Delphi, HOW TO DELETE AN ELEMENT FROM A COLLECTION? Is this possible? Have i to use another type of data?
Hope you've understood the idea.




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Does An Array Contain An Element?
I'm using PHP 4.4.4. Is there a shorter way to check if an array has
an element besides doing a for loop and iterating through each element?

Is The Element Of An Array The Last One ?
What is the best way to solve the next problem: PHP Code:

Getting Element Only Once In Array
I've got an array like so: 1,1,5 But I want to try and make it so if it has the ID appearing more than once then it won't be in the array multiple times. i.e. I want the above to say 1,5.

How To Get Array Element?
get_the_category() returns an array that looks like this:

ResourceArray ( [0] =stdClass Object ( [cat_ID] =3 [cat_name] =>
Certifications [category_nicename] =ms-certifications
[category_description] =Certification Resource [category_parent] =0
[category_count] =5 [fullpath] =/ms-certifications ) )

I want to get the value in "category_description" and have tried:

$category = get_the_category();
$cat_d = $category->category_description;
print_r($cat_d);

But that doesn't print anything. What is the correct way to get the
value I'm after?

Array Element
I am having trouble getting a weather sticker php script to work properly. I have been working with the guys that wrote it, but so far they haven't come up with a solution. They/we have narrowed it down to the section of the script that compares a text string (which has been converted into UPPER CASE) from a file generated by the weather station, with an array. It is supposed to match an index in the array, that points to which graphic file to generate. This works about 30% of the time.

(When the text string is VERY SIMPLE - like CLOUDY or CLEAR or RAIN) But not when the text string is more complex, like HEAVY RAIN, MIST OVERCAST, LIGHT RAIN or PARTLY CLOUDY.

Here is the line that defines one of the elements in the array:

Quote $vws_icon["PARTLY|MOSTLY+CLOUDY|SUNNY+THUNDERSTORM"] = "./icons/" . "$daynight" . "_tstorm.$image_format";

I did not incluse the whole script, nor the whole array because of its length.

My Question (Finally...) is --- in the line above within the square braces, he has enclosed a string in double quotes, but the string is delimited by | characters and + characters. Can someone explain to me in English what this means? I have tried reading through two big reference books on php arrays, and they only made me even less certain. (For example: "the line means - If the string is PARTLY or MOSTLY CLOUDY or SUNNY and THUNDERSTORM, then set $vws_icon to whtever the $daynight._tstorm.$image_format evaluates to.)

I know, my example translation makes NO SENSE in English. Maybe it makes no sense in php either? I think what he's trying to ask is "If the string contains 'THUNDERSTORM' and any of these other words, then generate the correct icon file for thunderstorm".

Deleting An Element In An Array??
Here is the problem:

I've got an array with the following elements

$array = ("ice","ice","polka","skate","polka");

thats 2 polka, 2 ice and 1 skate

Now i want someway of removing just one of the polka's from it..

so that i'd be left with:
$array = ("ice","ice","skate","polka");

what i did was a basic search with for loop and break

Code: for($x=0;$x<sizeof($array);$x++)
{
if($array[$x] == "polka")
{
echo("match ".$x);
break;
}
} alls well n good till now.. now i've got the index value(2 in this case) of the element which needs to be deleted.. but what should be done now?? is there any function which'll let me delete a particular element in an array?

Is there any other way to go around this?

Deleting An Element From An Array
I'm not being an idiot here and missing something very obvious as I seem to be prone to doing.

I have the following code:

Editing An Element Within An Array
I have a two-dimensional array that looks like this:
array(
array(0, 123),
array(0, 234),
array(0, 345),
array(0, 456)
)
I want to REMOVE any element that contains 234, and I want to
INCREMENT the first value for any element that contains 345, to make
it look like this:
array(
array(0, 123),...

How To Substract An Element From An Array
I'm looking for a function which substracts an element from an array. For example,

$array = array ("green", "red", "blue", "grey" );

array_substract($array, "red" );

now it's like I had :

$array = array ("green", "blue", "grey" );

notice that the order should be preserved!

Missing Array Element
I am trying to store the id's for 3 hotel rooms into an array called
$rooms, using a simple mysql select statement. Here is the code:

<?php require_once('Connections/Vita_Italiano.php'); ?>
<?php mysql_select_db($database_Vita_Italiano, $Vita_Italiano);
$query_rsAllRooms = "SELECT * FROM room";

$rsAllRooms = mysql_query($query_rsAllRooms, $Vita_Italiano) or
die(mysql_error());

$row_rsAllRooms = mysql_fetch_assoc($rsAllRooms);
$totalRows_rsAllRooms = mysql_num_rows($rsAllRooms);

// create array of all rooms
while ($row_rsAllRooms = mysql_fetch_assoc($rsAllRooms))
{
$rooms[]= $row_rsAllRooms['Room_Number'];
}

?>

When I use <?php print_r($rooms);?> to display the contents of the
variable, the array only contains 2 room numbers, instead of 3. These
are stored in $rooms[0] and $rooms[1].

Does anyone have any ideas what is going on here?

Missing Element In Array?!
I have the following query I run to pull some data from the db. The
sql (when run on the db) returns 2 elements. However, if I var dump my
variable ($aidlook) then the first element in the array does not show
up.

$getaid = mysql_query("SELECT a_uid FROM `answers` WHERE `qid` =
$qid", $db);
$aidlook = mysql_fetch_array($getaid,MYSQL_NUM);

Doing a var dump returns: array(1) { [0]= string(1) "4" }

I should be getting 2 elements (4 and 5).

I am totally baffled. code as follows:

*********************
if (!is_array($aidlook)) $aidlook = array($aidlook); // Check for the
existence of the array in case of null returns

if (!in_array($userid,$aidlook)) // Look for our element which in
this case is "5"
{
if ($qstatus === 1) // Do a status check
{
}

answer_box($qid,$answ); // additional function being run

} else
{
echo "Your Text Here";

}
}

Deleting An Element Of An Array?
How can I delete an Element of an array? Consider the following Example: PHP Code:

Eliminate An Element Of An Array
I want to eliminate the last element of an array, couse when I print it, it doesn´t have any value. I tried to use array_pop but it doesn´t work.

Deleting An Element From An Array
is there some handy and short method to delete an element from an array and than shifting the rest of elements one place ahead
e.g

array(1,2,3,4,5,6)
becomes
array(1,2,4,5,6)

Remove Element From Array
How do I remove an element from an array? Here is my current code:

$sql = mysql_query("SELECT suitenos FROM gssettings WHERE id=1");
$row = mysql_fetch_assoc($sql);
$suites = split(",",$row['suitenos']);
$number_of_suites = count($suites);
for($i=0;$i<$number_of_suites;$i++)
{
if($suiteno == $suites[$i])
{
$selected = "SELECTED";
} else {
$selected = "";
}

echo<<<endhtml
<option value="$suites[$i]" $selected>$suites[$i]</option>
endhtml;
}

Now I have another table in my database called "gsdays" that holds values of suite numbers that are already booked. What I want to do is remove any suite numbers that are already booked from my $suites array. To get the booked suites, I would do the following query.

$query = mysql_query("SELECT suite FROM gsdays WHERE date='2007-03-24'");
$row = mysql_fetch_assoc($query);

$booked_suites = $row['suite'];

so basically what I want to do is remove $booked_suites from $suites. I tried using array_splice but I don't know what I'm doing.

Random Element From An Array
seems simple enough, but not as much as rand($ARRAY); how would i select a random element from an array?

ie $User_Prize = rand($Users);

Check If An Element Exist Within An Array
I thought there must be a simple function that checks if an element exist within an array. I can't find it anywhere... does anybody know?

How To Control Which Element Of An Array Is Printed
Anyone know how to control which element of an array is printed, say from 1-4 then 5-9 etc.

Removing Element From Array Using String
I am trying the following based on an example from php.net

<?php

$array_of_items = array ('A','B','C','D');
array_splice($array_of_items, 'B', 1);

foreach ($array_of_items as $array_of_items2)
{
Print $array_of_items2;}?>

I expect the result to be ACD, I am getting BCD, Not sure why.

Insert An Element In Numbered Array
I need to do the following:

Say I have a multidim array:

$array = array();

$array[0]['name'] = 'Kevin'
$array[0]['age'] = 23;

$array[1]['name'] = 'Julia'
$array[1]['age'] = 31;

$array[2]['name'] = 'Bob'
$array[2]['age'] = 26;

$array[3]['name'] = 'Drew'
$array[3]['age'] = 37;

and I have a seperate array:

$person = array();
$person['name'] = 'Dana'
$person['age'] = 33;

now I want to insert the $person array into the $array in such a way
that it ends up at index 1 and the subsequent elements get pushed up and
renumbered, so $array[1] becomes $array[2] and so on.

Does php have a built-in function that does this?

How To Add An Element To The Middle Of An Associative Array ?
I got an array that consists of elements that are arrays also. Now I
wish I could add an element to the middle of it. Let mi give you an
example:

array (
- array(1,15,apple),
- array(2,28,banana),
- array(3,41,orange)
}

I would like to add, let's say, carrot on 2nd position:

array (
- array(1,15,apple),
- array(2,57,carrot),
- array(3,28,banana),
- array(4,41,orange)
}

Array_splice() does not work (or maybe i use it in a wrong way? - it
splits an adding element for, in that case, 3 elements). Array_push()
adds only to the end of an array. can samobody tell me how to add and
element to the middle of an associative array?

Changing A Value Of An Element In A Two Dimensional Array
I am having a problem with array manipulation.

in my php script i am reading from a csv file.
the content of file is like this:

Removing An Element From The POST Array
I have a form that is posting it data to PHP_SELF. This then gets processed and does it's thing. My question is that when I hit the submit button, I get all the data from my form but I also get one item from the Submit button itself. Can I make the submit button not include itself in the POST?

Here is an example output of print_r($_POST)
Array
(
    [ACPlatSearch] => -1
    [ACDeedSearch] => -1
    [ACUserInfo] => -1
    [ACPropertySearch] => -1
    [ACStatsTotalSales] => -1
    [SavePermissions] => Save
)

The last element is the submit button, the other ones are checkboxes.  I don't want that last one.  So is there a simple way to not include it or do I need to loop through the array and remove it manually?  I need the rest of the array intact for further processing with array functions.

Randomly Selecting An Element In An Array That Has Not Been Selected Before..
Im having problems in randomly selecting an element in an array that
has not been selected before.. in other words, I have an array of
answers to questions, then I want to select 5, with one of them being
the correct answer to the question, and the others not..
Here is my code.. (I already have the correct answer at array position
[0])

for($i=1;$i<=4;$i++)
{
//choose a random number in array range
$phraseArr_random_answer=rand(1,$phraseArr_size);
// check to see if random selection has not already been chosen

for($j=0;$j<=$i;$j++)
{
//check to see if element has already been chosen (j is current
array)
echo">> ".$answerArr[$j][2] ."<< >>".
$phraseArr[$phraseArr_random_answer][2]."<< <br />";
if(strcmp($answerArr[$j][2],$phraseArr[$phraseArr_random_answer][2]))
{
$alreadyUsed="FALSE";
$i--;
//document.writeln("choices[j] = " + choices[j] + " and i = " + i
// + " and viet[random_choice] = " + viet[random_choice] + "<br
/>");
//break;
echo"test";
}
else
{
$alreadyUsed="TRUE";/*
}
}
//add a random selection from phraseArr into each element of
answerArr
if ($alreadyUsed=="TRUE")
{
$answerArr[$j][2]=$phraseArr[$phraseArr_random_answer][2];
}

$answerArr[$i]=$phraseArr[$phraseArr_random_answer][2];
echo $answerArr[$i]." - ";
}

Thanks to anyone who can tell me the problem with this..

Referencing An Array Element With A String Variable
I've been researching this for hours and can't seem to find the right
syntax.

I need to retrieve a value of an array by referencing the element using a
string variable.

For example:

$data['lastname'] = 'hank'
$element = 'lastname'
echo $data[$element];

Calling A Function Inside An Array Element Txt Str
Long story short – I don’t have access to a DB, so I’ve done what I think is the next best thing; I’ve defined my Web-link addresses in an external file (global variables) and I include the HREFlist in all PHP docs. Next, and the part that causes question, I made a (really spiffy) function that writes out the <a href…> part.

I have an array of quotes from people who are saying things and I’d like to hyperlink keywords in their quotes. Ideally, this would mean several calls to the linkWriter() function. My initial attempts culminated with me finally throwing in the towel and I just hard-coded the HTML tags, although I was able to interject the global variables into the array variables so I didn’t have to hard-code the URLs....

Address Element Of The Array Formed By Query To Database
I am making a function wherein if a query is passed it returns the result set cursor. Now before I return the cursor, I would like to process each element of the array. How do I address each element of the array, considering the field names are as per the query and not known. The function is

function useforquerytodb($thequery){
global $PHP_SELF, $DATABASE;
return mysql_db_query($DATABASE,$thequery);}

Fopen And Filename As Array Element (code Included)
i have a piece of code that reads a csv list.
For instance:
1,index.html
2,linux.html

I read these in an array and then i want to use the filename
(2nd array element) to make a file and write something in it.
However, i always get the error:
Warning: fopen(index.html ): failed to open stream: Invalid argument in
E:DATAstartpagegenerate.php on line 34
Cannot open file

The code that gives problems is this and more specificaly the titel var
if (!$file_handle = fopen($titel,'a')) { echo "Cannot open file
".$titel; die; }

If i for instance change this $titel to "index.html" then i do not get
warnings.
So it probably has to do with how $titel is presented.
I tried wrapping $titel in double qoute, that doesn't work either.
I tried wrapping $titel in single qoutes but that off course uses $titel as
the
name of the file instead of the content of the variable.

How can i make this work?

Code:
====
<?php
$PAGES = "pages.txt";

$data = 'This '
$data .= 'is a '
$data .= 'string.'

/* open pages parse them and make the pages */
$file = file($PAGES);

foreach ($file as $line) {
$arTemp = explode(",",$line);
$aPages[$arTemp[0]] = $arTemp[1];
echo "Making ".$arTemp[1]." with id ".$arTemp[0]."
";
unset($arTemp);
}

foreach ($aPages as $sleutel => $titel) {
print "Huidige waarde van $aPages: $sleutel, $titel.
";
/* write file*/
if (!$file_handle = fopen($titel,'a')) { echo "Cannot open file
".$titel; die; }
if (!fwrite($file_handle, $data)) { echo "Cannot write to file
".$titel; die; }
fclose($file_handle);
}
?>

Delete From Array
let's say I have an array $letters(a,b,c,d,e,f) is there a function that will remove 'd' from the middle. I'm looking for something like array_delete($letters,'d');

Delete/drop Value From An Array
Hi,

I have an array of values that I am matching against a string and I want to drop the value from the array if it is in the string.

My array looks like:
0=>val1, 1=>val2, etc

I understand how to check to see if the value is in the array, but not how do get rid of it if it is.

How To Clear/delete An Array?
I am using an array in a loop, and every time I loop I need to have the array be empty.

I cannot find an array function to empty the array, or clear it.

Have I missed something somewhere ( I suspect I have) ?

Delete Item From Array
How do I search for an item within an array, then delete it?

How Do I Delete Items From Array?
I can add several items to the basket, but how do I delete one from the basket? I want to delete any of the added items. Here is my code for creating the array and adding items to it.

// creating the array
$item = array();
$item['id'] = "1";
$item['price'] = "100";
$item['quantity'] = "1";

// add item
$_SESSION['basket'][] = $item;

Delete An Item From An Index Array?
How can I delete an Item from an index array in php4?

Safe To Delete Elements Of Array In Foreach
Is it safe to remove elements from an array that foreach is working on?
(normally this is not the case but not sure in php) If so is there an
efficient way to handle it? (I could add the indexes to a temp array and
delete afterwards if necessary but since I'm actually working in a nested
situation this could get a little messy. I guess I could set there values to

How To Walk Array And Delete Matched Elements?
I'm kind of lost on this one - I need to modify 2 files based on user input:

Add Element On The Page
I'm creating a web page to allow the user to change their web page by filling the form. In my form, I use JavaScript to change the properties on their page at the iframe in the same page on my form page. I know Javascript is the client programming, that can change the content of the file in server. I also use PHP to handle to change the content of file (web page) in server. It is not difficult to change the properties on the page at the iframe, however, if i want to allow the user to add element, let says adding a paragraph below the paragraph is existed on the page. How can I add more elements(image, link, heading...etc.) on the page or any function can do so?? How can do it in screen (change the visual page) maybe by JavaScript and how can change the content by using PHP?

Remove Element
I have an array I have included below, it is created by whatever is posted from the previous page. I would like it to remove all of the blank elements if possible. Code:

Foreach Element In $_POST?
Is there a way to go through each element in the $_POST supervariable?

I'm making a page with dynamic forms, so I don't know for sure how many
$_POST variables there will be (the number of textboxes, radio buttons,
etc changes).

How can I either count them or do a foreach loop to do this?

Random Element(s) Select?
I'm trying to create a page that displays an image, but also has a specific text string and link associated with that image. There are 5 images, and I want a way to select randomly one of these images with its appropriate info.

I've seen a lot of scripts already that select an image from a text file, or a database, or a directory of images, but I want to do it with arrays. I suppose I would have to use associative arrays. PHP Code:

Breaks In Form Element
I have been having a whole lot of trouble trying to get this to work. I am using the code below for my Content Management system. The field 'content' is the field that needs to have the auto <br /> turned off. I am using the code below to insert pages into the database. The pages have HTML included within them and are formatted using Dreamweaver, so they look nice and neat.

After the script is done running, the page entered had extra <br />s added to it. Could someone please help me get rid of them, been looking all over the place and have tried a lot, no luck though PHP Code:

How To Change Css Id In Span Element?
How to change a link's color based on a php variable?

I have a number of links on a page:

<p><a href="page1.php">Page 1</a></p>
<p><a href="page2.php">Page 2</a></p>
<p><a href="page3.php">Page 3</a></p>
<p><a href="page4.php">Page 4</a></p>

I want the link to be red if $nav has a value that corresponds to the page
number: If $nav = 1, then the page1.php link should be red; if $nav = 2,
then the page2.php link should be red, and so on.

This is how I'd normally code the html to make a red link:

<p><span id="red"><a href="page1.php">Page 1</a></span></p>

But how do I check the value of $nav and insert the appropriate span id for
each link? Can I somehow make the span id a variable? How to I jump in and
out of php within a tag?

If $nav does not correspond with the link's page number, then the link
should remain the default color - which is blue:

<p><span id="blue"><a href="page1.php">Page 1</a></span></p>

Add A PHP Element To An HTML Page?
I have a .htm page on which I want to add a PHP script that will display links depending on if the user is in session or not. I'm not sure if this can be done on a strictly .htm page, but hey you only live once right?  Here's the script I'm attempting to execute:

   <? if ($_SESSION['auth'] == "yes"){ ?>
       <a href="/index.php?page=sign_in">Sign In[/url]
             <? }else{ ?>
       <a href="index.php?page=logout">Logout[/url]
   <? } ?>

The problem is that I don't know all the back-end php coding for the 3rd party s/w I'm using, but since the design calls for a "main .htm page" that displays all the "include" pages, having 2 links displaying on the same page seems silly (1 link for login and anohter for logout).

Xml_parse In Loop Only Returning First Element
I'm working on my first attempt to parse some XML I've generated from an SQL query and I'm having some trouble with the xml_parse function.

As you can see from the code snippet, I'm iterating through a multidimensional array that holds the XML.

The loop/nested loop execute correctly but the xml_parse only returns the first XML element it encounters. I've read the manual regarding the xml_parse function but I don't quite understand the isFinal portion of the syntax in this context. I understand using it to detect eof if reading from a file but I'm not sure how it works while reading from the arrays I've created.

I've echoed several tests going through the loops and the data is available. I'm stumped.

Can someone point me in the correct direction?

Thanks!


Snippet:
for($i=0; $i<count($contentXMLKeys); $i++) {
for($j=0; $j<count($contentXMLSubKeys); $j++) {
xml_parse($xmlParser, $contentXML[$contentXMLKeys[$i]][$contentXMLSubKeys[$j]]);
}
}

The handlers are setup to echo html tags and content on a switch/case basis.

function startElement($parser, $name, $attrs) {
switch($name) {
case 'HEADLINE':
echo '<h4>'
break;
}
}

function characterData($parser, $data) {
echo $data;
}

function endElement($parser, $name) {
switch($name) {
case 'HEADLINE':
echo '</h4>'
break;
}
}

Numerical Element Key In Foreach Loop
I have this nice little array: PHP Code:

DOM XML - How To Append A Link Element As A Child
I'm trying to generate a RSS newsfeed using the DOM XML functions, but you
already know that if you read my previous post .

I'm able to create rss, channel and title elements but not a link element.
The following code sample doesn't generated
<link>http://www.websitetitle.com</link> but <link> like if the DOM XML
forgot to close the element :

<?php
$link_el = $dom_doc->create_element ('link');
$link_el = $channel_el->append_child ($link_el);
$link_el->set_content ('http://www.websitetitle.com');
?>

Then I got some crazy idea. I thought that maybe DOM XML was thinking the
link element I created was a specially element, not an enclosed one, like in
XHTML for example :

<link rel="stylesheet" type="text/css" href="styles.css" />

Crazy crazy because I don't see why DOM XML would handle my elements as HTML
elements... But then I tried with a meta tag, and guess what... It also
doesn't work ! It works with enclosed elements, tags, like title, head,
html, body or unknown ones like channel or item. But it doesn't work with
link, meta and input elements !

And I have no clue why it handles these elements as special elements...

Here is the full script :

PEAR::HTML_QuickForm Select Element
I am trying to get a default value set for a "Select" element, like this:

$f = new HTML_QuickForm("request", "post", "", "_self", NULL,TRUE);
$f_priority = array ("Very low","Low","Normal","High","Very High");
$priority_element =& $f->addElement("select", "request_priority",
"Priority:", $f_priority);
$priority_element->setSelected("2");
....

But the html which is generated from this looks like this:

....
<option value="1">Low</option>
<option value="2" selected="selected">Normal</option>
<option value="3">High</option
....

To my understanding, it should only say "selected", not "selected="selected"

Is there some workaround, am I doing something wrong, or does one need
to hack QuickForm for this?

Random Element From That Text Document
Coud someone please send me a script which uses a text document which pulls out a random element from that text document (like a picture or some text),

Columns In A Form Select Element
Can this be done. I am wanting to have columns in my forms select element. I
have data of varied length from three fields. Can this be done, or should I
try and stuff spaces into the select element to asume columns


Copyright © 2005-08 www.BigResource.com, All rights reserved