简体   繁体   中英

php foreach loop in_array doesn't display positive result

Array ( [0] => Array ( [0] => Array ( [subject] => Computer [price] => 33.00 [quantity] => 1 ) ) )

I have an array like this above, but when i use in_array like below to check the subject value, it will display negative result.

foreach ($cart_info as $item){
    foreach ($item as $item2){
        if (in_array("Computer", $item2['subject'])) {
        echo "Yes";
        }else{
            echo "No";
        }   
    }
}   

haystack Should be an array

Please check the documentation for in_array

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

 haystack

    The array.
strict

    If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack.

Ref: http://in2.php.net/in_array

You are passing a wrong key so you are not getting desired output.

it should be

in_array("Computer", $cart_info[0]) 

or

in_array("Computer", $cart_info)

or even

 if($item2 == "Computer")

instead of

in_array("Computer", $item2['subject'])

try

if (in_array("Computer", $item2)) {
   echo "Yes";
}else{
   echo "No";
} 

Because $item2['subject'] is not an array. In your case use:

foreach ($cart_info as $item){
    foreach ($item as $item2){
        if ("Computer" == $item2['subject'])) {
        echo "Yes";
        }else{
            echo "No";
        }   
    }
}   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM