0

What am I doing wrong in the code below?

print_r(array_values($haystack));

returns the following:

Array ( [0] => Array ( [name] => album2 ) [1] => Array ( [name] => album3 ) [2] => Array ( [name] => Album 1 ) [3] => Array ( [name] => jopie99 ) [4] => Array ( [name] => kopie3 ) [5] => Array ( [name] => test56 ) [6] => Array ( [name] => rob7 ) ) testArray ( [0] => Array ( [name] => album2 ) [1] => Array ( [name] => album3 ) [2] => Array ( [name] => Album 1 ) [3] => Array ( [name] => jopie99 ) [4] => Array ( [name] => kopie3 ) [5] => Array ( [name] => test56 ) [6] => Array ( [name] => rob7 ) )

Now I have the following code:

$needle = 'album3';

if (in_array($needle, $haystack)) {   
    //do something 
}

At least the needle can be found somewhere in the haystack, but apparently not with the if statement given. Can someone help me out?

1

4 Answers 4

1

As you are using multidimentional array. you can use below method.

$needle = 'album3';
foreach($haystack as $h){
  if ( $h['name'] == $needle ){
     // do something...
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try using array_column along with in_array as

Note : PHP>=5.5

if(in_array($needle,array_column($arr,'name'))){
   //your code
}

or you can alternatively use as

if(in_array(['name' => $needle],$arr)){
    //your code
}

Comments

0

This should work for you:

Just go through each array value with array_walk_recursive() and check if the needle is equals the value. If yes simply set the result to true.

<?php

    $needle = 'album3';
    $arr = [["album1"],["album2"],["album4"],["album3"]];
    $result = FALSE;

    array_walk_recursive($arr, function($v, $k)use($needle, &$result){
        if($v == $needle)
            $result = TRUE;
    });

    var_dump($result);

?>

This works with every array no matter how many dimensions it has.

Comments

0

Try doing this using strict checking:

if (in_array($needle, $haystack, true))

Read the documentation for more info.

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.