0

I'm trying to loop through a PHP array but I only ever get back my original data. I think it has something to do with when I break the loop

$newData = $this->seperateKeyValuePairs($data);

private function seperateKeyValuePairs($array)
{
    foreach($array as $key => $item)
    {
      if( is_array($item) ) $this->seperateKeyValuePairs($item);

      if( is_string($key) && $this->stringStartsWith($key, 'is_') ) {
        $item = $this->makeBoolean($item);
      }

    }

    return $array;
}
2
  • 1
    Uh, this doesn't make much sense. Can you a.) show us the array?, and 2.) tell us what you mean by " I only ever get back my original data" Commented Sep 17, 2015 at 20:28
  • 1
    You are setting $item to a value, but that doesn't update the original array. You probably want foreach($array as $key => &$item), so that way you're using references and the array will get updated. Commented Sep 17, 2015 at 20:29

1 Answer 1

1

I think the problem is on this line:

$item = $this->makeBoolean($item);

You change the value of item. Item is not a pointer to the value in the array, but a copy of it, so the value in the array remains unchanged. What you want to do instead is this:

$array[$key] = $this->makeBoolean($item);

In the same spirit, you have to change

if( is_array($item) ) $this->seperateKeyValuePairs($item);

to

if( is_array($item) ) $array[$key] = $this->seperateKeyValuePairs($item);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. That was the trick. I completely overlooked passing the reference.

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.