Tuesday 4 September 2018

PHP in_array does not return the expected results

When I attempt to determine if a user is in an array of users, for some reason it is only returning true when the user is in the 0th position.

For the life of me I cannot figure out what I am doing wrong.

This does not echo "True"
echo $usersign; // RDW

print_r($these_analysts[0]); // Array ( [0] => JKB [1] => RDW )

if(in_array($usersign,$these_analysts[0])){
    echo "True";
}


This echoes "True"
echo $usersign; // RDW

print_r($these_analysts[0]); // Array ( [0] => RDW [1] => CLM )

if(in_array($usersign,$these_analysts[1])){
    echo "True";
}

EDIT:

vardump gives a much more comprehensive view of the array, whereas print_r did show the trailing spaces, it didn't catch my eye.
For some reason the first element of each array was giving string3, and all others were giving string4.

You have a lot of syntax errors.
When you use strings, it is always better prace to put strings in single or double quotes. It doesn't matter which one (as far as speed is concerned).
Also, you need commas between the elements.
I entered the following code and it works.
$usersign = 'RDW';
$these_analysts[0] = array( 'JKB', 'RDW' );
print_r( $these_analysts );
if(in_array($usersign,$these_analysts[0])) echo "True";

0 comments:

Post a Comment