Deleting single values from an array

Hello

-Extreme newbie teaching self PHP-

I am looking for a way to do the following :

  1. Take a variable $delete from user input
  2. Search an array for $delete and, if found, remove the value from the array.

I’ve tried the following (we’ll say $array has the data “order1111”, “order2222”, “order3333” and $delete=“order1111”) :

[php]foreach($array as $index=>$order)
{
if ($order=$delete)
{
unset($array[$index])
}
}[/php]

For whatever reason this doesn’t check to see if $order=$delete, it sets $order=$delete and doesn’t remove the value from the array.

Any help is appreciated. Thanks in advance.

if ($order=$delete) 

There’s part of your mistake – in an if statement, you always want a comparison operator, not an assignment operator. Therefore, use ==, not =.

You may be able to skip the loop and simply say
unset($array[$delete]);

If that triggers an error when you try to unset a nonexistent key, try
@unset($array[$delete]);
which will suppress the error.

Hey aixccapt99

Thanks for that, I’ll give it a try and see what happens.

I had thought about and tried the unset($array[$delete]), however I could only get UNSET to work when using the index numbers (ie UNSET ($array[0]) to delete the first value of the array). I couldn’t use it to reference the actual value, so I was using foreach($array as $index=>$value) to extract the index number/value pairs.

Hopefully you understand what I just said :) .

Thanks again!

$array[$index] = NULL

If you wanted to avoid errors and also check to see if the array contains what you are looking for then I would use the function in_array.

Example:

[php]<?
if(in_array("$look_for_this", $in_this_array)){
echo “This item is in the array”;
}
else{
echo “Couldn’t find what you were looking for!”;
}
?>[/php]

Thanks for all the help guys!

I have been able to accomplish the task using your suggestions (and a little extra debugging). I’m slowly learning.

If I have any other problems I’ll be back.

Thanks again!

Cheers

Sponsor our Newsletter | Privacy Policy | Terms of Service