1

I have an array with in which there is another array. I need to unset a index of the sub array.

array
  0 => 
    array
      'country_id' => string '1' (length=1)
      'description' => string 'test' (length=4)
  1 => 
    array
      'country_id' => string '2' (length=1)
      'description' => string 'sel' (length=5)
  2 => 
    array
      'country_id' => string '3' (length=1)
      'description' => string 'soul' (length=5)

Now i need to unset country_id of all the three index of the master array. I am using PHP and I initially thought unset will do until i realized my array is nested.

How can I do this?

3
  • foreach($array as &$element){unset($element['country_id'];} Commented Sep 10, 2014 at 12:33
  • foreach ($array as &$sub) unset($sub['country_id']); Commented Sep 10, 2014 at 12:33
  • possible duplicate of PHP - unset in a multidimensional array Commented Sep 10, 2014 at 12:52

4 Answers 4

0
foreach ($original_array as &$element) {
  unset($element['country_id']);
}

why &$element?

Because foreach (...) will perform a copy, so we need to pass the reference to the "current" element in order to unset it (and not his copy)

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

Comments

0
foreach($yourArray as &$arr)
{
   unset($arr['country_id']);
}

Comments

0
foreach ($masterArray as &$subArray)
    unset($subArray['country_id']);

The idea is that you take each sub array by reference and unset the key within that.


EDIT: another idea, just to make things interesting, would be to use the array_walk function.

array_walk($masterArray, function (&$item) { unset ($item['country_id']); });

I'm not sure that it's any more readable, and the function call will make it slower. Still, the option is there.

Comments

0

You need to use:

foreach ($array as &$item) {
  unset($item['country_id']);
}

but after loop you should really unset reference otherwise you might get into trouble so the correct code is:

foreach ($array as &$item) {
  unset($item['country_id']);
}
unset($item);

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.