(PHP 4, PHP 5, PHP 7, PHP 8)
in_array — Checks if a value exists in an array
Description
in_array(mixed $needle
, array $haystack
, bool $strict
= false
): bool
Parameters
-
needle
-
The searched value.
Note:
If
needle
is a string, the comparison is done
in a case-sensitive manner. -
haystack
-
The array.
-
strict
-
If the third parameter
strict
is set totrue
then the in_array() function will also check the
types of the
needle
in thehaystack
.Note:
Prior to PHP 8.0.0, a
string
needle
will match an array
value of0
in non-strict mode, and vice versa. That may lead to undesireable
results. Similar edge cases exist for other types, as well. If not absolutely certain of the
types of values involved, always use thestrict
flag to avoid unexpected behavior.
Return Values
Returns true
if needle
is found in the array,
false
otherwise.
Examples
Example #1 in_array() example
<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
if (in_array("mac", $os)) {
echo "Got mac";
}
?>
The second condition fails because in_array()
is case-sensitive, so the program above will display:
Example #2 in_array() with strict example
<?php
$a = array('1.10', 12.4, 1.13);
if (
in_array('12.4', $a, true)) {
echo "'12.4' found with strict checkn";
}
if (
in_array(1.13, $a, true)) {
echo "1.13 found with strict checkn";
}
?>
The above example will output:
1.13 found with strict check
Example #3 in_array() with an array as needle
<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');
if (
in_array(array('p', 'h'), $a)) {
echo "'ph' was foundn";
}
if (
in_array(array('f', 'i'), $a)) {
echo "'fi' was foundn";
}
if (
in_array('o', $a)) {
echo "'o' was foundn";
}
?>
The above example will output:
'ph' was found 'o' was found
See Also
- array_search() – Searches the array for a given value and returns the first corresponding key if successful
- isset() – Determine if a variable is declared and is different than null
- array_key_exists() – Checks if the given key or index exists in the array
beingmrkenny at gmail dot com ¶
11 years ago
Loose checking returns some crazy, counter-intuitive results when used with certain arrays. It is completely correct behaviour, due to PHP's leniency on variable types, but in "real-life" is almost useless.
The solution is to use the strict checking option.
<?php// Example array$array = array(
'egg' => true,
'cheese' => false,
'hair' => 765,
'goblins' => null,
'ogres' => 'no ogres allowed in this array'
);// Loose checking -- return values are in comments
// First three make sense, last four do not
in_array(null, $array); // true
in_array(false, $array); // true
in_array(765, $array); // true
in_array(763, $array); // true
in_array('egg', $array); // true
in_array('hhh', $array); // true
in_array(array(), $array); // true
// Strict checking
in_array(null, $array, true); // true
in_array(false, $array, true); // true
in_array(765, $array, true); // true
in_array(763, $array, true); // false
in_array('egg', $array, true); // false
in_array('hhh', $array, true); // false
in_array(array(), $array, true); // false?>
leonhard dot radonic+phpnet at gmail dot com ¶
6 months ago
I got an unexpected behavior working with in_array. I'm using following code:
<?php
// ...
$someId = getSomeId(); // it gets generated/fetched by another service, so I don't know what value it will have. P.S.: it's an integer
// The actual data in my edge-case scenario:
// $someId = 0;
// $anyArray = ['dataOne', 'dataTwo'];
if (in_array($someId, $anyArray)) {
// do some work
}
// ...
?>
With PHP7.4, in_array returns boolean true.
With PHP8.1, in_array returns boolean false.
It took me quite some time to find out what's going on.
rhill at xenu-directory dot net ¶
14 years ago
I found out that in_array will *not* find an associative array within a haystack of associative arrays in strict mode if the keys were not generated in the *same order*:
<?php
$needle
= array(
'fruit'=>'banana', 'vegetable'=>'carrot'
);$haystack = array(
array('vegetable'=>'carrot', 'fruit'=>'banana'),
array('fruit'=>'apple', 'vegetable'=>'celery')
);
echo
in_array($needle, $haystack, true) ? 'true' : 'false';
// Output is 'false'echo in_array($needle, $haystack) ? 'true' : 'false';
// Output is 'true'?>
I had wrongly assumed the order of the items in an associative array were irrelevant, regardless of whether 'strict' is TRUE or FALSE: The order is irrelevant *only* if not in strict mode.
Armands Rieksti ¶
3 months ago
I'd like to point out that, if you're using Enum data structures and want to compare whether an array of strings has a certain string Enum in it, you need to cast it to a string.
From what I've tested, the function works correctly:
if the array is filled with strings and you're searching for a string;
if the array is filled with Enums and you're searching for an Enum.
Anonymous ¶
6 months ago
$a = new StdClass();
$b = new StdClass();
// Expected: false, got: true
var_dump(in_array($a, [$b]));
// bool(true)
// Works fine
var_dump(in_array($a, [$b], true));
// bool(false)
thomas dot sahlin at gmail dot com ¶
13 years ago
If you're creating an array yourself and then using in_array to search it, consider setting the keys of the array and using isset instead since it's much faster.
<?php
$slow
= array('apple', 'banana', 'orange');
if (
in_array('banana', $slow))
print('Found it!');$fast = array('apple' => 'apple', 'banana' => 'banana', 'orange' => 'orange');
if (isset(
$fast['banana']))
print('Found it!');?>
Anonymous ¶
6 months ago
$a = new StdClass();
$b = new StdClass();
// Expected: false, got: true
var_dump(in_array($a, [$b]));
// bool(true)
// Works fine
var_dump(in_array($a, [$b], true));
// bool(false)
За последние 24 часа нас посетили 12127 программистов и 1255 роботов. Сейчас ищут 557 программистов …
in_array
(PHP 4, PHP 5, PHP 7)
in_array — Проверяет, присутствует ли в массиве значение
Описание
bool in_array
( mixed $needle
, array $haystack
[, bool $strict
= FALSE
] )
Список параметров
-
needle
-
Искомое значение.
Замечание:
Если
needle
– строка, сравнение
будет произведено с учетом регистра. -
haystack
-
Массив.
-
strict
-
Если третий параметр
strict
установлен в
TRUE
тогда функция in_array()
также проверит соответствие типов
параметраneedle
и соответствующего
значения массиваhaystack
.
Возвращаемые значения
Возвращает TRUE
, если needle
был найден
в массиве, и FALSE
в обратном случае.
Примеры
Пример #1 Пример использования in_array()
<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Нашел Irix";
}
if (in_array("mac", $os)) {
echo "Нашел mac";
}
?>
Второго совпадения не будет, потому что in_array()
регистрозависима, таким образом, программа выведет:
Пример #2 Пример использования in_array() с параметром strict
<?php
$a = array('1.10', 12.4, 1.13);
if (
in_array('12.4', $a, true)) {
echo "'12.4' найдено со строгой проверкойn";
}
if (
in_array(1.13, $a, true)) {
echo "1.13 найдено со строгой проверкойn";
}
?>
Результат выполнения данного примера:
1.13 найдено со строгой проверкой
Пример #3 Пример использования in_array() с массивом в качестве параметра needle
<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');
if (
in_array(array('p', 'h'), $a)) {
echo "'ph' найденоn";
}
if (
in_array(array('f', 'i'), $a)) {
echo "'fi' найденоn";
}
if (
in_array('o', $a)) {
echo "'o' найденоn";
}
?>
Результат выполнения данного примера:
Смотрите также
- array_search() – Осуществляет поиск данного значения в массиве и возвращает
соответствующий ключ в случае удачи - isset() – Определяет, была ли установлена переменная значением отличным от NULL
- array_key_exists() – Проверяет, присутствует ли в массиве указанный ключ или индекс
Вернуться к: Функции для работы с массивами
How can I search and find, for a given target value, the closest value in an array?
Let’s say I have this exemplary array:
array(0, 5, 10, 11, 12, 20)
For example, when I search with the target value 0, the function shall return 0; when I search with 3, it shall return 5; when I search with 14, it shall return 12.
asked Mar 28, 2011 at 20:51
0
Pass in the number you’re searching for as the first parameter and the array of numbers to the second:
function getClosest($search, $arr) {
$closest = null;
foreach ($arr as $item) {
if ($closest === null || abs($search - $closest) > abs($item - $search)) {
$closest = $item;
}
}
return $closest;
}
answered Mar 28, 2011 at 20:56
Tim CooperTim Cooper
157k38 gold badges327 silver badges278 bronze badges
5
A particular lazy approach is having PHP sort the array by the distance to the searched number:
$num = 3;
$array = array(0, 5, 10, 11, 12, 20);
$smallest = [];
foreach ($array as $i) {
$smallest[$i] = abs($i - $num);
}
asort($smallest);
print key($smallest);
Dharman♦
30.3k22 gold badges84 silver badges132 bronze badges
answered Mar 28, 2011 at 21:01
mariomario
144k20 gold badges236 silver badges289 bronze badges
0
This is high-performance function I wrote for sorted big arrays
Tested, main loop needs only ~20 iterations for an array with 20000 elements.
Please mind array has to be sorted (ascending)!
define('ARRAY_NEAREST_DEFAULT', 0);
define('ARRAY_NEAREST_LOWER', 1);
define('ARRAY_NEAREST_HIGHER', 2);
/**
* Finds nearest value in numeric array. Can be used in loops.
* Array needs to be non-assocative and sorted.
*
* @param array $array
* @param int $value
* @param int $method ARRAY_NEAREST_DEFAULT|ARRAY_NEAREST_LOWER|ARRAY_NEAREST_HIGHER
* @return int
*/
function array_numeric_sorted_nearest($array, $value, $method = ARRAY_NEAREST_DEFAULT) {
$count = count($array);
if($count == 0) {
return null;
}
$div_step = 2;
$index = ceil($count / $div_step);
$best_index = null;
$best_score = null;
$direction = null;
$indexes_checked = Array();
while(true) {
if(isset($indexes_checked[$index])) {
break ;
}
$curr_key = $array[$index];
if($curr_key === null) {
break ;
}
$indexes_checked[$index] = true;
// perfect match, nothing else to do
if($curr_key == $value) {
return $curr_key;
}
$prev_key = $array[$index - 1];
$next_key = $array[$index + 1];
switch($method) {
default:
case ARRAY_NEAREST_DEFAULT:
$curr_score = abs($curr_key - $value);
$prev_score = $prev_key !== null ? abs($prev_key - $value) : null;
$next_score = $next_key !== null ? abs($next_key - $value) : null;
if($prev_score === null) {
$direction = 1;
}else if ($next_score === null) {
break 2;
}else{
$direction = $next_score < $prev_score ? 1 : -1;
}
break;
case ARRAY_NEAREST_LOWER:
$curr_score = $curr_key - $value;
if($curr_score > 0) {
$curr_score = null;
}else{
$curr_score = abs($curr_score);
}
if($curr_score === null) {
$direction = -1;
}else{
$direction = 1;
}
break;
case ARRAY_NEAREST_HIGHER:
$curr_score = $curr_key - $value;
if($curr_score < 0) {
$curr_score = null;
}
if($curr_score === null) {
$direction = 1;
}else{
$direction = -1;
}
break;
}
if(($curr_score !== null) && ($curr_score < $best_score) || ($best_score === null)) {
$best_index = $index;
$best_score = $curr_score;
}
$div_step *= 2;
$index += $direction * ceil($count / $div_step);
}
return $array[$best_index];
}
ARRAY_NEAREST_DEFAULT
finds nearest elementARRAY_NEAREST_LOWER
finds nearest element which is LOWERARRAY_NEAREST_HIGHER
finds nearest element which is HIGHER
Usage:
$test = Array(5,2,8,3,9,12,20,...,52100,52460,62000);
// sort an array and use array_numeric_sorted_nearest
// for multiple searches.
// for every iteration it start from half of chunk where
// first chunk is whole array
// function doesn't work with unosrted arrays, and it's much
// faster than other solutions here for sorted arrays
sort($test);
$nearest = array_numeric_sorted_nearest($test, 8256);
$nearest = array_numeric_sorted_nearest($test, 3433);
$nearest = array_numeric_sorted_nearest($test, 1100);
$nearest = array_numeric_sorted_nearest($test, 700);
answered Mar 13, 2014 at 10:21
PeterPeter
16.3k8 gold badges50 silver badges77 bronze badges
7
<?php
$arr = array(0, 5, 10, 11, 12, 20);
function getNearest($arr,$var){
usort($arr, function($a,$b) use ($var){
return abs($a - $var) - abs($b - $var);
});
return array_shift($arr);
}
?>
answered Mar 28, 2011 at 21:06
WrikkenWrikken
68.9k8 gold badges96 silver badges136 bronze badges
2
Tim’s implementation will cut it most of the time. Nevertheless, for the performance cautious, you can sort the list prior to the iteration and break the search when the next difference is greater than the last.
<?php
function getIndexOfClosestValue ($needle, $haystack) {
if (count($haystack) === 1) {
return $haystack[0];
}
sort($haystack);
$closest_value_index = 0;
$last_closest_value_index = null;
foreach ($haystack as $i => $item) {
if (abs($needle - $haystack[$closest_value_index]) > abs($item - $needle)) {
$closest_value_index = $i;
}
if ($closest_value_index === $last_closest_value_index) {
break;
}
}
return $closest_value_index;
}
function getClosestValue ($needle, $haystack) {
return $haystack[getIndexOfClosestValue($needle, $haystack)];
}
// Test
$needles = [0, 2, 3, 4, 5, 11, 19, 20];
$haystack = [0, 5, 10, 11, 12, 20];
$expectation = [0, 0, 1, 1, 1, 3, 5, 5];
foreach ($needles as $i => $needle) {
var_dump( getIndexOfClosestValue($needle, $haystack) === $expectation[$i] );
}
answered Oct 14, 2014 at 17:41
GajusGajus
67.8k70 gold badges271 silver badges434 bronze badges
To search the nearest value into an array of objects you can use this adapted code from Tim Cooper’s answer.
<?php
// create array of ten objects with random values
$images = array();
for ($i = 0; $i < 10; $i++)
$images[ $i ] = (object)array(
'width' => rand(100, 1000)
);
// print array
print_r($images);
// adapted function from Tim Copper's solution
// https://stackoverflow.com/a/5464961/496176
function closest($array, $member, $number) {
$arr = array();
foreach ($array as $key => $value)
$arr[$key] = $value->$member;
$closest = null;
foreach ($arr as $item)
if ($closest === null || abs($number - $closest) > abs($item - $number))
$closest = $item;
$key = array_search($closest, $arr);
return $array[$key];
}
// object needed
$needed_object = closest($images, 'width', 320);
// print result
print_r($needed_object);
?>
answered Oct 31, 2015 at 16:43
quantmequantme
3,5894 gold badges33 silver badges49 bronze badges
Best method I’ve found based on Piyush Dholariya’s answer:
$array = [4, 9, 15, 6, 2];
$goal = 7;
$closest = array_reduce($array, function($carry, $item) use($goal) {
return (abs($item - $goal) < abs($carry - $goal) ? $item : $carry);
}, reset($array)); // Returns 6
answered Jan 14, 2021 at 11:19
Thomas BachemThomas Bachem
1,5171 gold badge16 silver badges10 bronze badges
This is the same approach as Mario’s answer, but I use array_search()
and min()
instead of sorting. The performance is the same, so it just comes down to the matter of preference.
function findClosest(array $values, $match)
{
$map = [];
foreach ($values as $v) {
$map[$v] = abs($match - $v);
}
return array_search(min($map), $map);
}
answered Dec 16, 2021 at 12:34
Dharman♦Dharman
30.3k22 gold badges84 silver badges132 bronze badges
You can simply use array_search
for that, it returns one single key, if there are many instances of your search found within the array, it would return the first one it finds.
Quote from PHP:
If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.
Example Usage:
if(false !== ($index = array_search(12,array(0, 5, 10, 11, 12, 20))))
{
echo $index; //5
}
Update:
function findNearest($number,$Array)
{
//First check if we have an exact number
if(false !== ($exact = array_search($number,$Array)))
{
return $Array[$exact];
}
//Sort the array
sort($Array);
//make sure our search is greater then the smallest value
if ($number < $Array[0] )
{
return $Array[0];
}
$closest = $Array[0]; //Set the closest to the lowest number to start
foreach($Array as $value)
{
if(abs($number - $closest) > abs($value - $number))
{
$closest = $value;
}
}
return $closest;
}
answered Mar 28, 2011 at 21:07
RobertPittRobertPitt
56.7k21 gold badges113 silver badges161 bronze badges
2
Considering that the input array is sorted in ascending order asort()
for example, you’ll be far faster to search using a dichotomic search.
Here’s a quick and dirty adaptation of some code I’m using to insert a new event in an Iterable event list sorted by DateTime objects…
Thus this code will return the nearest point at the left (before / smaller).
If you’d like to find the mathematically nearest point: consider comparing the distance of the search value with the return value and the point immediately at the right (next) of the return value (if it exists).
function dichotomicSearch($search, $haystack, $position=false)
{
// Set a cursor between two values
if($position === false)
{ $position=(object) array(
'min' => 0,
'cur' => round(count($haystack)/2, 0, PHP_ROUND_HALF_ODD),
'max' => count($haystack)
);
}
// Return insertion point (to push using array_splice something at the right spot in a sorted array)
if(is_numeric($position)){return $position;}
// Return the index of the value when found
if($search == $haystack[$position->cur]){return $position->cur;}
// Searched value is smaller (go left)
if($search <= $haystack[$position->cur])
{
// Not found (closest value would be $position->min || $position->min+1)
if($position->cur == $position->min){return $position->min;}
// Resetting the interval from [min,max[ to [min,cur[
$position->max=$position->cur;
// Resetting cursor to the new middle of the interval
$position->cur=round($position->cur/2, 0, PHP_ROUND_HALF_DOWN);
return dichotomicSearch($search, $haystack, $position);
}
// Search value is greater (go right)
// Not found (closest value would be $position->max-1 || $position->max)
if($position->cur < $position->min or $position->cur >= $position->max){return $position->max;}
// Resetting the interval from [min,max[ to [cur,max[
$position->min = $position->cur;
// Resetting cursor to the new middle of the interval
$position->cur = $position->min + round(($position->max-$position->min)/2, 0, PHP_ROUND_HALF_UP);
if($position->cur >= $position->max){return $position->max;}
return dichotomicSearch($search, $haystack, $position);
}
answered Jan 27, 2018 at 16:05
llangellange
7572 gold badges10 silver badges14 bronze badges
Binary search to find closest value (array must be sorted):
function findClosest($sortedArr, $val)
{
$low = 0;
$high = count($sortedArr) - 1;
while ($low <= $high) {
if ($high - $low <= 1) {
if (abs($sortedArr[$low] - $val) < abs($sortedArr[$high] - $val)) {
return $sortedArr[$low];
} else {
return $sortedArr[$high];
}
}
$mid = (int)(($high + $low) / 2);
if ($val < $sortedArr[$mid]) {
$high = $mid;
} else {
$low = $mid;
}
}
// Empty array
return false;
}
answered Apr 26, 2021 at 18:03
Dima L.Dima L.
3,38332 silver badges30 bronze badges
function closestnumber($number, $candidates) {
$last = null;
foreach ($candidates as $cand) {
if ($cand < $number) {
$last = $cand;
} elseif ($cand == $number) {
return $number;
} elseif ($cand > $number) {
return $last;
}
}
return $last;
}
mickmackusa
43.1k12 gold badges80 silver badges132 bronze badges
answered Mar 28, 2011 at 21:00
k to the zk to the z
3,2072 gold badges27 silver badges41 bronze badges
2
I’ll provide a late answer that endeavors to avoid needless iterations and excessive function calls by maintaining two temporary variables and implementing an early return.
An elegant solution should not require a time complexity greater than n — in other words, the big O should be O(n) and the little o should be o(1). The big O only gets worse by pre-sorting the haystack, then iterating the haystack again. To get achieve o(1), you will need an early return when an identical match is encountered — there is no need to search further.
My snippet will arbitrarily return the first occurring value with the lowest distance (in case multiple values have the same distance). Any other behavior is not specified by the OP.
A trivial performance improvement over some other answers is that abs()
is the lone function call within the loop and it is called a maximum of 1 time per iteration. Some previous answers recalculate the distance of the current value as well as the current closest match on each iteration — this is more work than is necessary.
Code: (Demo)
$haystack = [-6, 0, 5, 10, 11, 12, 20];
$needles = [0, 3, 14, -3];
function getNearest($needle, $haystack) {
if (!$haystack) {
throw new Exception('empty haystack');
}
$bestDistance = PHP_INT_MAX;
foreach ($haystack as $value) {
if ($value === $needle) {
return $needle;
}
$distance = abs($value - $needle);
if ($distance < $bestDistance) {
$bestDistance = $distance;
$keep = $value;
}
}
return $keep ?? $value; // coalesce to silence potential IDE complaint
}
foreach ($needles as $needle) { // each test case
echo "$needle -> " . getNearest($needle, $haystack) . "n";
}
Output:
0 -> 0
3 -> 5
14 -> 12
-3 -> -6
answered Dec 15, 2021 at 23:53
mickmackusamickmackusa
43.1k12 gold badges80 silver badges132 bronze badges
Summary: in this tutorial, you will learn how to use the PHP in_array()
function to check if a value exists in an array.
Introduction to the PHP in_array() function
The in_array()
function returns true
if a value exists in an array. Here’s the syntax of the in_array()
function:
in_array ( mixed $needle , array $haystack , bool $strict = false ) : bool
Code language: PHP (php)
In this syntax:
$needle
is the searched value.$haystack
is the array to search.$strict
if the$strict
sets totrue
, thein_array()
function will use thestrict
comparison.
The in_array()
function searches for the $needle
in the $haystack
using the loose comparison (==
). To use the strict comparison (===
), you need to set the $strict
argument to true
.
If the value to check is a string, the in_array()
function will search for it case-sensitively.
The in_array()
function returns true
if the $needle
exists in the $array
; otherwise, it returns false
.
PHP in_array() function examples
Let’s take some examples of using the in_array()
function.
1) Simple PHP in_array() function examples
The following example uses the in_array()
function to check if the value 'update'
is in the $actions
array:
<?php
$actions = [
'new',
'edit',
'update',
'view',
'delete',
];
$result = in_array('update', $actions);
var_dump($result); // bool(true)
Code language: HTML, XML (xml)
It returns true
.
The following example returns false
because the publish
value doesn’t exist in the $actions
array:
<?php
$actions = [
'new',
'edit',
'update',
'view',
'delete',
];
$result = in_array('publish', $actions);
var_dump($result); // bool(false)
Code language: HTML, XML (xml)
The following example returns false
because the value 'New'
doesn’t exist in the $actions
array. Note that the in_array()
compares the strings case-sensitively:
<?php
$actions = [
'new',
'edit',
'update',
'view',
'delete',
];
$result = in_array('New', $actions);
var_dump($result); // bool(false)
Code language: HTML, XML (xml)
2) Using PHP in_array() function with the strict comparison example
The following example uses the in_array()
function to find the number 15
in the $user_ids
array. It returns true
because the in_array()
function compares the values using the loose comparison (==
):
<?php
$user_ids = [10, '15', '20', 30];
$result = in_array(15, $user_ids);
var_dump($result); // bool(true)
Code language: HTML, XML (xml)
To use the strict comparison, you pass false
to the third argument ($strict
) of the in_array()
function as follows:
<?php
$user_ids = [10, '15', '20', 30];
$result = in_array(15, $user_ids, true);
var_dump($result); // bool(false)
Code language: HTML, XML (xml)
This time the in_array()
function returns false
instead.
3) Using PHP in_array() function with the searched value is an array example
The following example uses the in_array()
function with the searched value is an array:
<?php
$colors = [
['red', 'green', 'blue'],
['cyan', 'magenta', 'yellow', 'black'],
['hue', 'saturation', 'lightness']
];
if (in_array(['red', 'green', 'blue'], $colors)) {
echo 'RGB colors found';
} else {
echo 'RGB colors are not found';
}
Code language: HTML, XML (xml)
Output:
RGB colors found
4) Using PHP in_array() function with an array of objects example
The following defines the Role
class that has two properties $id
and $name
:
<?php
class Role
{
private $id;
private $name;
public function __construct($id, $name)
{
$this->id = $id;
$this->name = $name;
}
}
Code language: HTML, XML (xml)
This example illustrates how to use the in_array()
function to check if a Role
object exists in an array of Role
objects:
<?php
// Role class
$roles = [
new Role(1, 'admin'),
new Role(2, 'editor'),
new Role(3, 'subscribe'),
];
if (in_array(new Role(1, 'admin'), $roles)) {
echo 'found it';
}
Code language: HTML, XML (xml)
Output:
found it!
If you set the $strict
to true
, the in_array()
function will compare objects using their identities instead of values. For example:
// Role class
$roles = [
new Role(1, 'admin'),
new Role(2, 'editor'),
new Role(3, 'subscribe'),
];
if (in_array(new Role(1, 'admin'), $roles, true)) {
echo 'found it!';
} else {
echo 'not found!';
}
Code language: PHP (php)
Output:
not found!
Summary
- Use PHP
in_array()
function to check if a value exists in an array.
Did you find this tutorial useful?
In this article, we will see how to find the value in the array using the in_array() function in PHP, & will also understand its implementation through the examples.
The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.
Syntax:
bool in_array( $val, $array_name, $mode )
Parameters: The in_array() function accepts 3 parameters, out of which 2 are compulsory and another 1 is optional. All three parameters are described below:
- $val: This is a required parameter that specifies the element or value to be searched in the given array. This parameter can be of mixed type i.e, it can be of string type or integer type, or any other type. If this parameter is of string type then the search will be performed in a case-sensitive manner.
- $array_name: This is a required parameter and it specifies the array in which we want to search.
- $mode: This is an optional parameter and is of boolean type. This parameter specifies the mode in which we want to perform the search. If it is set to TRUE, then the in_array() function searches for the value with the same type of value as specified by the $val parameter. The default value of this parameter is FALSE.
Return Value: The in_array() function returns a boolean value i.e, TRUE if the value $val is found in the array otherwise it returns FALSE.
Approach: In order to search an array for a specific value, we will be using the in_array() function where the parameter for the search is of string type & its value is set to true. Otherwise, this function returns a false value if the specified value is not found in an array.
We will understand the concept of the in_array() function in PHP, through the example.
Example 1: The below program performs the search using the in_array() function in non-strict mode ie, the last parameter $mode is set to false which is its default value. The value to be searched is of string type whereas this value in the array is of integer type still the in_array() function returns true as the search is in non-strict mode.
<?php
$marks
=
array
(100, 65, 70, 87);
if
(in_array(
"100"
,
$marks
))
{
echo
"found"
;
}
else
{
echo
"not found"
;
}
?>
Example 2: The below program performs the search using the in_array() function in strict mode ie., the last parameter $mode is set to true and the function will now also check the type of values.
PHP
<?php
$name
=
array
(
"ravi"
,
"ram"
,
"rani"
, 87);
if
(in_array(
"ravi"
,
$name
, TRUE))
{
echo
"found n"
;
}
else
{
echo
"not found n"
;
}
if
(in_array(87,
$name
, TRUE))
{
echo
"found n"
;
}
else
{
echo
"not found n"
;
}
if
(in_array(
"87"
,
$name
, TRUE))
{
echo
"found n"
;
}
else
{
echo
"not found n"
;
}
?>
Output
found found not found
Reference: http://php.net/manual/en/function.in-array.php
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
Last Updated :
03 Dec, 2021
Like Article
Save Article