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?
asked Jan 18, 2015 at 13:38
-
Do you only want to delete [id] => 1 from that subarray, or the whole parent array (with key 0 in this case) ?edwardmp– edwardmp2015年01月18日 13:41:12 +00:00Commented Jan 18, 2015 at 13:41
-
1foreach is the way to gogskema– gskema2015年01月18日 13:41:29 +00:00Commented Jan 18, 2015 at 13:41
-
@edwardmp I would like to delete the whole parent array (with key 0 in this case)Shairyar– Shairyar2015年01月18日 13:42:04 +00:00Commented Jan 18, 2015 at 13:42
2 Answers 2
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
answered Jan 18, 2015 at 13:43
Sign up to request clarification or add additional context in comments.
Comments
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;
}
}
answered Jan 18, 2015 at 13:50
Comments
lang-php