1. php
  2. /references
  3. /in-array

PHP in_array() Function

PHP's in_array() checks if a value exists in an array.

Here is a quick example:

<?php
$fruits = array('apple', 'banana', 'orange', 'grape');

if (in_array('apple', $fruits)) {
    echo 'Apple is in the array';
} else {
    echo 'Apple is not in the array';
}

Syntax and Parameters

in_array($value, $array, $type)
ParameterDescriptionOptional/Required
$valueThe value to search forRequired
$arrayThe array to search inRequired
$typeIf the type parameter is set to TRUE, the function will also match the types of the value and the elements in the arrayOptional

The in_array() function will return a boolean value of TRUE if the value is found in the array, and FALSE if it is not found.

Here are a few additional examples of how the in_array() function is typically used:

<?php
$colors = array('red', 'green', 'blue');

if (in_array('red', $colors)) {
    echo 'Red is in the array';
}

$numbers = array(1, 2, 3, 4, 5);

if (in_array(3, $numbers)) {
    echo '3 is in the array';
}

$users = array(
    array('id' => 1, 'name' => 'John'),
    array('id' => 2, 'name' => 'Jane'),
    array('id' => 3, 'name' => 'Bob')
);

if (in_array(array('id' => 2, 'name' => 'Jane'), $users)) {
    echo 'Jane is in the array';
}

Other related functions include:

array_key_exists() - checks if a key exists in an array

array_search() - searches an array for a value and returns the key if it is found

in_multiarray() - searches a multidimensional array for a value and returns TRUE if it is found