Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check if a value exists in an array

Short answer

in_array() looks for a value. A third argument of true turns on strict, type-aware comparison:

<?php
 
var_dump(in_array('green', ['red', 'green', 'blue'], true));

Output:

bool(true)

Checking for a key

array_key_exists() and isset() check for a key. The difference is that isset() returns false when the value is null:

<?php
 
$user = ['name' => 'Anna', 'city' => null];
 
var_dump(array_key_exists('city', $user));
var_dump(isset($user['city']));

Output:

bool(true)
bool(false)

Finding the position

If you need the key of the matching element, use array_search():

<?php
 
var_dump(array_search('green', ['red', 'green', 'blue'], true));

Output:

int(1)

Functions used in this recipe

  • in_array — Checks whether a value exists in an array.
  • array_search — Searches an array for a value and returns its key.

Thanks for reading!

Donate to the site — we work hard for you.