maximus
maximus

Reputation: 53

PHP error in_array() [function.in-array]: Wrong datatype for second argument

I get the following error for the second argument even when I set the global in the function for it. The second argument is an array.

in_array() [function.in-array]: Wrong datatype for second argument

$cat_id

Array ( [0] => 76 [1] => 89 [2] => 81 ) 

PHP

for ($x = 0; $x < count($query_cat_id); $x++){
    if(in_array($query_cat_id[$x], $cat_id)){
    //
    }
}

Upvotes: 2

Views: 10204

Answers (2)

vishalakshi
vishalakshi

Reputation: 39

Write (array) before the second argument of your in_array().

Upvotes: 3

Luke Stevenson
Luke Stevenson

Reputation: 10351

Change your code to the following:

$cat_id = array( 0 => 76 , 1 => 89 , 2 => 81 ); 

for( $x = 0 , $c = count( $query_cat_id ) ; $x < $c ; $x++ ){
  if( in_array( $query_cat_id[$x] , (array) $cat_id ) ){
    // MATCH FOUND
  }
}

1) If the code provided in your Question was as-is, the way you declared your array was unusual (and possibly faulty), 2) Including (array) before $cat_id should ensure that it is handled as an array, even if it is actually a string (it gets instantly converted into an array for the purpose of that function).

I realise that these suggestions may not be accurate, as they are based off the data you copied and pasted into SO, as opposed to the actual data in the scripts, but they may give you a place to start.

Possible Alternate Solution

If the purpose of the code is to compare two arrays, and perform some action when values are found to be within both, the following may be a faster way to perform this work:

$cat_id = array( 0 => 76 , 1 => 89 , 2 => 81 ); 
//$query_cat_id is assumed as set to an array already

$matched_cat_ids = array_intersect( (array) $query_cat_id , (array) $cat_id );

foreach( $matched_cat_ids as $k => $v ){
  // Perform work required on MATCH for Value "$v"
}

That is assuming you need specific work performed for each match. If you simply want to know whether a match has occurred, checking that count($matched_cat_ids) is greater than zero should suffice.

Upvotes: 3

Related Questions