Php in array несколько значений

PHP in_array() Function

Search for the value «Glenn» in an array and output some text:

$people = array(«Peter», «Joe», «Glenn», «Cleveland»);

if (in_array(«Glenn», $people))
echo «Match found»;
>
else
echo «Match not found»;
>
?>

Definition and Usage

The in_array() function searches an array for a specific value.

Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.

Syntax

Parameter Values

Parameter Description
search Required. Specifies the what to search for
array Required. Specifies the array to search
type Optional. If this parameter is set to TRUE, the in_array() function searches for the search-string and specific type in the array.

Technical Details

Return Value: Returns TRUE if the value is found in the array, or FALSE otherwise
PHP Version: 4+
PHP Changelog: PHP 4.2: The search parameter may now be an array

More Examples

Example

$people = array(«Peter», «Joe», «Glenn», «Cleveland», 23);

if (in_array(«23», $people, TRUE))
echo «Match found
«;
>
else
echo «Match not found
«;
>
if (in_array(«Glenn»,$people, TRUE))
echo «Match found
«;
>
else
echo «Match not found
«;
>

if (in_array(23,$people, TRUE))
echo «Match found
«;
>
else
echo «Match not found
«;
>
?>

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

in_array

Searches for needle in haystack using loose comparison unless strict is set.

Parameters

Note:

If needle is a string, the comparison is done in a case-sensitive manner.

If the third parameter strict is set to true then the in_array() function will also check the types of the needle in the haystack .

Note:

Prior to PHP 8.0.0, a string needle will match an array value of 0 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 the strict flag to avoid unexpected behavior.

Return Values

Returns true if needle is found in the array, false otherwise.

Examples

Example #1 in_array() example

$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

if ( in_array ( ‘12.4’ , $a , true )) echo «‘12.4’ found with strict check\n» ;
>

if ( in_array ( 1.13 , $a , true )) echo «1.13 found with strict check\n» ;
>
?>

The above example will output:

1.13 found with strict check

Example #3 in_array() with an array as needle

if ( in_array (array( ‘p’ , ‘h’ ), $a )) echo «‘ph’ was found\n» ;
>

if ( in_array (array( ‘f’ , ‘i’ ), $a )) echo «‘fi’ was found\n» ;
>

if ( in_array ( ‘o’ , $a )) echo «‘o’ was found\n» ;
>
?>

The above example will output:

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

User Contributed Notes 8 notes

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.

$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

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

I got an unexpected behavior working with in_array. I’m using following code:

// .
$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.

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*:

$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.

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.

Here is a recursive in_array function:

$myNumbers = [
[ 1 , 2 , 3 , 4 , 5 ],
[ 6 , 7 , 8 , 9 , 10 ],
];

$array = [
‘numbers’ => $myNumbers
];

// Let’s try to find number 7 within $array
$hasNumber = in_array ( 7 , $array , true ); // bool(false)
$hasNumber = in_array_recursive ( 7 , $array , true ); // bool(true)

function in_array_recursive ( mixed $needle , array $haystack , bool $strict ): bool
foreach ( $haystack as $element ) if ( $element === $needle ) return true ;
>

$isFound = false ;
if ( is_array ( $element )) $isFound = in_array_recursive ( $needle , $element , $strict );
>

if ( $isFound === true ) return true ;
>
>

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.

$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!’ );

Источник

Дополнения к функции in_array()

PHP-функция in_array() проверяет, присутствует ли в массиве значение:

$array = array("Mac", "NT", "Irix", "Linux"); if (in_array('Irix', $array))

Но в некоторых моментах её будет не достаточно, далее подробнее:

Проверка сразу нескольких значений в массиве

Если требуется проверить наличие сразу нескольких значений в массиве – функция in_array_all() .

function in_array_all($needles, $haystack)

Пример использования:

$array = array('Mac', 'NT', 'Irix', 'Linux'); if (in_array_all(array('Mac', 'Win'), $array)) < echo 'true'; >else < echo 'false'; // Выведется false т.к. в $array нет 'Win' >

Одно из нескольких значений в массиве

Если требуется проверить вхождение хотя бы одного из нескольких значений, подойдет функция in_array_any() .

function in_array_any($needles, $haystack)

Пример использования:

$array = array('Mac', 'NT', 'Irix', 'Linux'); if (in_array_any(array('Mac', 'Win'), $array)) < echo 'true'; // Выведется true т.к. в $array есть 'Mac' >else

in_array для многомерного массива

Для поиска значения в многомерном массиве поможет функция in_array_r() :

function in_array_r($needle, $haystack, $strict = false) < foreach ($haystack as $item) < if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) < return true; >> return false; >

Пример использования:

$array = array( 0 => array('Mac'), 1 => array('NT'), 2 => array('Irix'), 3 => array('Linux') ); if (in_array_r('Mac', $array)) < echo 'true'; // Выведется true >else

Комментарии

Другие публикации

Сортировка массивов

В продолжении темы работы с массивами поговорим о типичной задаче – их сортировке. Для ее выполнения в PHP существует множество функций, их подробное описание можно посмотреть на php.net, рассмотрим.

PHP функции для checked и selected

Две мини функции которые облегчают выделения полей select, radio и checkbox до и после отправки форм.

Автоматическое сжатие и оптимизация картинок на сайте

Изображения нужно сжимать для ускорения скорости загрузки сайта, но как это сделать? На многих хостингах нет.

Источник

Читайте также:  Basic Web Page
Оцените статью