2

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?

3 Answers 3

3

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().

Sign up to request clarification or add additional context in comments.

Comments

1

You can use array_map() instead of array_filter()

$arr1 = array_map(function($tmp) { unset($tmp['images']); return $tmp; }, $arr); 

print_r($arr1);

Comments

0

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);

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.