1

I'm writing a function to loop through an array until a match is found based on another array. However the value is returning null.

My example:

$i = 1;
$tmp = ['fff'=>111,'aaa'=>100,'ddd'=>99,'ccc'=>87,'eee'=>45,'bbb'=>3,'ggg'=>1];
$prg = ['bbb','ccc'];
function doFilter($tmp,$prg,$i) {                   
    $second = array_slice($tmp, $i, 1);
    $snd = key($second);
    if (!in_array(strtolower($snd),$prg)) {
        $i++;
        doFilter($tmp,$prg,$i);
    } else {
        // echo ccc
        echo $snd;
        return $snd;
    }                   
}
$snd = doFilter($tmp,$prg,$i);
// echo NULL
echo $snd;

Any thoughts why the value within the function is not being returned to populate the variable as a response from the function?

5
  • Why are you doing this recursively? Also, are you just trying to see if 1 $prg is in $tmp or you want to see all $prg that are in $tmp? Commented Apr 20, 2017 at 19:58
  • 1
    You don't return the value from the inner recursive calls.You probably want return doFilter($tmp,$prg,$i); Commented Apr 20, 2017 at 20:01
  • 1
    But really: array_intersect(array_keys($tmp), $prg) Commented Apr 20, 2017 at 20:03
  • fantastic, thanks! yes, was not returning the recursive loop. Commented Apr 20, 2017 at 20:04
  • but yes, there is probably an easier way to do it, although comparing keys in one array to values in the other. Commented Apr 20, 2017 at 20:04

1 Answer 1

1

This can all be efficiently done with array_intersect() and array_keys().

Code (Demo):

$tmp = ['fff'=>111,'aaa'=>100,'ddd'=>99,'ccc'=>87,'eee'=>45,'bbb'=>3,'ggg'=>1];
$prg = ['bbb','ccc'];

echo "1st Key: ",(sizeof($result=array_intersect(array_keys($tmp),$prg))==0?"Not Found":current($result));
echo "\n\nResult Array: ";
var_export($result);

Output:

1st Key: ccc

Result Array: array (
  3 => 'ccc',
  5 => 'bbb',
)

Alternatively if you want to get the value of the first match:

var_export(current(array_intersect_key($tmp,array_flip($prg))));
// Will ouput: 87
// if no matches, will return FALSE
Sign up to request clarification or add additional context in comments.

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.