Ryan D
Ryan D

Reputation: 751

PHP check if string exist in array not working

I am trying to see if a vin number exist in an array with no luck. Here is my array structure -

$vin[] = array($data);

Array ( [0] => Array ( [0] => 1C6RR7FG2JS178810 ) [1] => Array ( [0] => 1C6RR7FG2JS178810 ) [2] => Array ( [0] => 1C6RR7FG2JS178810 ) [3] => Array ( [0] => 1C6RR7FG2JS178810 )

And method for checking the array using in_array -

if (in_array("1C6RR7FG2JS178810", $vin)){ 
    echo "found"; 
}else{ 
    echo "not found"; 
} 

But shows not found every time even though I know it does exist. Where am I going wrong?

Upvotes: 2

Views: 862

Answers (2)

JEX
JEX

Reputation: 109

Your type of appending variable in array appends second array to 0 key in array and creates multidimensional array.

$array[] = ['someX'];

if (in_array('someX', $array[0])){
  echo "yes";
}

In this example someX variable is on 0 key, so the array will look like this:

Array
(
    [0] => Array
        (
            [0] => someX
        )

)

If you decide to use multidimensional array please look at this link: in_array() and multidimensional array

if(array_search('1C6RR7FG2JS178810', array_column($vin, "0")) !== false) {
    echo 'value is in multidim array';
}
else {
    echo 'value is not in multidim array';
}

Upvotes: 1

dWinder
dWinder

Reputation: 11642

Notice your array element are array with 1 element. You can use array_column to extract them. Consider:

if (in_array("1C6RR7FG2JS178810", array_column($vin, "0"))){ 
    echo "found"; 
} else { 
    echo "not found"; 
} 

I suspect you not adding the data right. Notice using $vin[] = array($data); is adding data to $vin elements wrap by array - I guess you should do just $vin[] = $data; (this probably goes in some loop...

Upvotes: 1

Related Questions