Question

I needed a function that recursively parses a multi-dimensional array for a (part) of a certain string value and, if found, returns the entire value the string is contained in.

I came up with the following solution:

function & ransackArray(array & $haystack, $needle) {
    foreach($haystack as &$element) {
        if(is_array($element)){
            if($v=ransackArray($element, $needle))
                return $v;
        } else {
            if(strstr($element, $needle))
                return $element;
        }
    }
    return false;
}    

This works fine. For instance, providing:

$data=array(
  'key' => 'something',
  'children' => array(
    'someValue' => 'myTest',
    'someMore' => 'yes'
  )
);    

And running:

$r=ransackArray($data, 'myTes');

This will result in $r containing 'myTest'.

The problem is that now that i found this value, i want to change it in $data, right on the fly, by writing:

$r='new value';

Which should then effectively result in data looking like this:

$data=array(
  'key' => 'something',
  'children' => array(
    'someValue' => 'new value',
    'someMore' => 'yes'
  )
);

This however, doesn't seem to work. Perhaps i misunderstand something about references. In any case, the reason i needed this to work is why i pass $haystack as a reference and also return the function's result as one.

Can this be done? If yes, how? And if not - why not?

Was it helpful?

Solution

You're missing two ampersands...one on this line:

if($v = self::ransackArray($element, $needle))

which should be:

if($v = &self::ransackArray($element, $needle))

and one on this line:

$r = ransackArray($data, 'myTes');

which should be:

$r = &ransackArray($data, 'myTes');

(Note: it looks like your ransackArray function is actually a method in a class, so if you're calling that method from within the class it would be $r = &$this->ransackArray($data, 'myTes');)

When passing variables to a function, you don't need to use & - just put the & in front of the parameter in the function signature - but in cases like yours where you are getting a return value from a function, there needs to be a & both in the function call and in the function signature. For more info see http://www.php.net/manual/en/language.references.pass.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top