0

I have an array like this:

$arr = [
        ['id' => 12, 'name' => 'Martin', 'cellphone' => '0019949437'],
        ['id' => 15, 'name' => 'Alex', 'cellphone' => "00183847394"]
       ];

I need to remove the cellphone item from array above. I wrote an code to do that like this:

$res = array_filter($arr, function($arr){ unset($arr['cellphone']); return $arr; });

But still that item exists and the $res is the same as $arr. What's wrong? What unset doesn't happen?

Martin AJ
  • 6,261
  • 8
  • 53
  • 111
  • Why are you trying to use `array_filter` for this to begin with, this would be much more a use case for `array_walk`. – CBroe Oct 14 '21 at 09:21
  • `unset` won't work since `$arr` isn't a ref to the real array. Use a loop. – 0stone0 Oct 14 '21 at 09:22
  • @CBroe Well, I want to filter a item of an array. I don't know anyway, probably array map or array walk are better choice in this case. – Martin AJ Oct 14 '21 at 09:23
  • The purpose of `array_filter` would be to _completely_ remove items from `$arr` - that is not what you want to do to begin with, you want to modify the items. – CBroe Oct 14 '21 at 09:26

2 Answers2

1

array_filter

Filters elements of an array using a callback function

Since you're trying to alter the nested array, array_filter wont work.

Use a loop, something like a foreach() or array_walk() should be fine.


<?php

// Input
$arr = [
   ['id' => 12, 'name' => 'Martin', 'cellphone' => '0019949437'],
   ['id' => 15, 'name' => 'Alex', 'cellphone' => "00183847394"]
];

// Using foreach
foreach($arr as &$tmp) {
   unset($tmp['cellphone']);
}

// Same result, using array_map
array_walk($arr, function (&$tmp) { unset($tmp['cellphone']); });

// Show result
var_dump($arr);

Here we loop over $arr, use & to get the reference to the deeper array, and use unset() to remove the cellphone.

Result:

array(2) {
  [0]=>
  array(2) {
    ["id"]=>
    int(12)
    ["name"]=>
    string(6) "Martin"
  }
  [1]=>
  &array(2) {
    ["id"]=>
    int(15)
    ["name"]=>
    string(4) "Alex"
  }
}

Try it online!

0stone0
  • 34,288
  • 4
  • 39
  • 64
0

Using array_map : It returns an array containing the results of applying the callback

$arr = [
    ['id' => 12, 'name' => 'Martin', 'cellphone' => '0019949437'],
    ['id' => 15, 'name' => 'Alex', 'cellphone' => "00183847394"]
];

function unsetCellPhone($u){
  unset($u['cellphone']);
  return $u;
}

$res = array_map("unsetCellPhone", $arr);

print_r($res);

Demo

navnath
  • 3,548
  • 1
  • 11
  • 19