Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't 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 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!

like image 671
thomaskessel Avatar asked Jan 12 '13 20:01

thomaskessel


1 Answers

You're looking for array_key_exists(), not in_array(), since you are searching for a specific key, not searching the values:

if( array_key_exists('1001', $products))
like image 124
nickb Avatar answered Oct 06 '22 21:10

nickb