I don't want to use foreach loop in my code and to unset array element from the array so I tried below code but it is not working as expected.
<?php
$arr = array(array('0'=>'test','1'=>'test1','images'=>'data'),array('0'=>'test','1'=>'test1','images'=>'data'),array('0'=>'test','1'=>'test1','images'=>'data'),array('0'=>'test','1'=>'test1','images'=>'data'));
$arr1 = array_filter($arr,function ($item) use ($my_value) {
if(array_key_exists('images',$item)) {unset($item['images']);}
return $item;});
echo "<pre>";
print_r($arr1);
echo "</pre>";
die;
I want to remove key 'images' from the array but this code returns actual array.
What is the error in this code?
Use array_map() instead of using array_filter
,
The array_map()
will map each value of your array and create a new array with new values with new operations performed.
$arr1 = array_map(function($tmp) { unset($tmp['images']); return $tmp; }, $arr);
Here is a Reference Link for array_map() .
You can use array_map() instead of array_filter()
$arr1 = array_map(function($tmp) { unset($tmp['images']); return $tmp; }, $arr);
print_r($arr1);
You can do this by updating existing array without assigning new array
You can use this:
array_walk($ararray_walk($arr, function(&$v, $k) { // Pass the values by reference
if(array_key_exists('images', $v)){
unset($v['images']);
}
});
print_r($arr);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.