1

I have an array $products that looks like this

Array
(
    [services] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [icon] => bus.png
                    [name] => Web Development
                    [cost] => 500
                )

            [1] => Array
                (
                    [id] => 4
                    [icon] => icon.png
                    [name] => Icon design
                    [cost] => 300
                )

        )

)

I am trying to delete the part of array that matches [id] => 1 and for this I am using the following code

$key = array_search('1', $products);
unset($products['services'][$key]);

However it is not working and I am not getting any error either. What am i doing wrong?

3
  • Do you only want to delete [id] => 1 from that subarray, or the whole parent array (with key 0 in this case) ? Commented Jan 18, 2015 at 13:41
  • 1
    foreach is the way to go Commented Jan 18, 2015 at 13:41
  • @edwardmp I would like to delete the whole parent array (with key 0 in this case) Commented Jan 18, 2015 at 13:42

2 Answers 2

3

This should work for you:

$key = array_search('1', $products["services"]);
                                //^^^^^^^^^^^^ See here i search in this array
unset($products['services'][$key]);

print_r($products);

Output:

Array ( [services] => Array ( [1] => Array ( [id] => 4 [icon] => icon.png [name] => Icon design [cost] => 300 ) ) )

And if you want to reindex the array, so that it starts again with 0 you can do this:

$products["services"] = array_values($products["services"]);

Then you get the output:

Array ( [services] => Array ( [0] => Array ( [id] => 4 [icon] => icon.png [name] => Icon design [cost] => 300 ) ) )
                            //^^^ See here starts again with 0
Sign up to request clarification or add additional context in comments.

Comments

2

This will loop through $products['services'] and delete the array whose 'id' key has value 1. array_values just re-indexes the array from 0 again.

foreach($products['services'] as $key => $service)
{
    if($product['id'] == 1)
    {
        unset($products['services'][$key]);
        array_values($products['services']);
        break;
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.