Cannot get in_array to work with associative array

I am having trouble trying to show that certain numbers (product numbers) exist in an associative array. When I try to execute this code, I always get "false".

<?php $products = array( '1000' => array('name' => 'Gibson Les Paul Studio', 'price' => 1099.99), '1001' => array('name' => 'Fender American Standard Stratocaster', 'price' => 1149.99), '1002' => array('name' => 'Jackson SL1 USA Soloist', 'price' => 2999.99) ); if (in_array('1001', $products)) { echo "true"; } else { echo "false"; } ?> 

I would really appreciate any help. Thanks!

+6
source share
2 answers

You are looking for array_key_exists() , not in_array() , since you are looking for a specific key, not a search for values:

 if( array_key_exists('1001', $products)) 
+23
source

Here you cannot use in_array () (checks if a value exists in the array).

Try array_key_exists () (checks if the specified array or index exists in the array).

 if (array_key_exists('1001', $products)) { echo "true"; } else { echo "false"; } 

You can even check for isset () and empty () keys.

+3
source

All Articles