2

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?

Ryan D
  • 677
  • 6
  • 24
  • 1
    Possible duplicate of [PHP multidimensional array search by value](https://stackoverflow.com/questions/6661530/php-multidimensional-array-search-by-value) – miken32 May 02 '19 at 22:03

2 Answers2

1

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...

dWinder
  • 11,359
  • 3
  • 19
  • 33
  • Yes this worked great thank you! $data was just a representation of my data, I dont actually use that variable but I understand what you are saying. – Ryan D May 02 '19 at 22:27
1

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';
}
JEX
  • 81
  • 1
  • 6
  • Thank you for the explanation, I figured it had something to do with the multi-dimensional array. This method still doesn't find the vin though for some reason. Would I need to go one step deeper i wonder? I originally tried this method earlier and had no luck as well.. – Ryan D May 02 '19 at 22:29
  • This method shows you that you need one step deeper of course, that's why I have used the $array[0] for demonstration. So if you are going to continue using multidimensional array I have updated answer for you under your request. – JEX May 02 '19 at 22:37