1

I have a multidimensional array called "values". This is how var_dump($values) looks now.

array(1) { 
    [0]=> array(3) { 
        ["content"]=> array(1) { 
            ["items"]=> array(4) { 
                [0]=> string(4) "3121" 
                [1]=> string(4) "3116" 
                [2]=> string(4) "3115" 
                [3]=> string(4) "3114" 
            } 
        } 
        ["options"]=> array(8) { 
            ["title"]=> string(7) "inherit" 
            ["size"]=> string(4) "tiny" 
            ["orderby"]=> string(4) "date" 
            ["order"]=> string(4) "desc" 
            ["filter"]=> string(8) "category" 
            ["pagination"]=> bool(false) 
            ["per_page"]=> int(12) 
            ["content"]=> array(3) { 
                [0]=> string(5) "title" 
                [1]=> string(7) "excerpt" 
                [2]=> string(4) "tags" 
            } 
        } 
        ["__version"]=> string(5) "2.3.1" 
    }
}

Here is the code i'm using to unset the value

 //before unset
    var_dump($values);

    $ID = "3121";
    foreach ($values as $value) {
                    foreach($value['content']['items'] as $key => $val) {               
                    if($val == $ID) {
                     unset($value['content']['items'][$key]);
                     }
                    }
        }

   //after unset
    var_dump($values);

My var_dump looks same even after unset. I think my array unset not working. Can someone tell me whats wrong with my code?

0

3 Answers 3

7

In php arrays are passed by value instead of by reference change

 foreach ($values as $value) {

to

 foreach ($values as &$value) {

See here for relevant documentation.

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

1 Comment

@Giri Remember to use unset($value) after the for loop has ended (this will delete the REFERENCE, NOT the variable), or you have a useless reference lying around in your code (which essentially means that if you delete the last value, eg. by using array.pop, it'll stay in memory, as you're referencing it somewhere else)
3

You didn't put a $key variable in the for loop and to change value you have to use a reference

foreach ($values as &$value) {
  foreach($value['content']['items'] as $key => $val) {               
      if($val == $ID) {
          unset($value['content']['items'][$key]);
      }
  }
}

1 Comment

Hey there, It still looks the same even after adding that key variable
0

foreach ($values as &$value)

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.