6

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!

2 Answers 2

23

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))
Sign up to request clarification or add additional context in comments.

1 Comment

That is exactly what I needed! I am pretty new to all the built-in php functions. Thanks!
3

You cannot use in_array() here (checks if a value exists in an array).

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

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

You can even check for key existance with isset() and empty().

1 Comment

Thank you for explaining it to me! That helps me out a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.