Looking for php Answers? Try Ask4KnowledgeBase
Looking for php Keywords? Try Ask4Keywords

PHP Checking if a value exists in array


The function in_array() returns true if an item exists in an array.

$fruits = ['banana', 'apple'];

$foo = in_array('banana', $fruits);
// $foo value is true

$bar = in_array('orange', $fruits);
// $bar value is false

You can also use the function array_search() to get the key of a specific item in an array.

$userdb = ['Sandra Shush', 'Stefanie Mcmohn', 'Michael'];
$pos = array_search('Stefanie Mcmohn', $userdb);
if ($pos !== false) {
    echo "Stefanie Mcmohn found at $pos";
PHP 5.x5.5

In PHP 5.5 and later you can use array_column() in conjunction with array_search().

This is particularly useful for checking if a value exists in an associative array:

$userdb = [
        "uid" => '100',
        "name" => 'Sandra Shush',
        "url" => 'urlof100',
        "uid" => '5465',
        "name" => 'Stefanie Mcmohn',
        "pic_square" => 'urlof100',
        "uid" => '40489',
        "name" => 'Michael',
        "pic_square" => 'urlof40489',

$key = array_search(40489, array_column($userdb, 'uid'));