Php принадлежит элементы in

in_array

Ищет в haystack значение needle . Если strict не установлен, то при поиске будет использовано нестрогое сравнение.

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

Замечание:

Если needle — строка, сравнение будет произведено с учетом регистра.

Если третий параметр strict установлен в TRUE тогда функция in_array() также проверит соответствие типов параметра needle и соответствующего значения массива haystack .

Возвращаемые значения

Возвращает TRUE , если needle был найден в массиве, и FALSE в обратном случае.

Примеры

Пример #1 Пример использования in_array()

$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

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

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() — Проверяет, присутствует ли в массиве указанный ключ или индекс

Источник

PHP in_array

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 ) : boolCode language: PHP (php)
  • $needle is the searched value.
  • $haystack is the array to search.
  • $strict if the $strict sets to true , the in_array() function will use the strict 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:

 $actions = [ 'new', 'edit', 'update', 'view', 'delete', ]; $result = in_array('update', $actions); var_dump($result); // bool(true)Code language: HTML, XML (xml)

The following example returns false because the publish value doesn’t exist in the $actions array:

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

 $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 ( == ):

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

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

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

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 :

 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:

 // 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)

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)

Summary

Источник

PHP: проверить, принадлежит ли элемент массиву

Я знаю, PHP 4 и PHP 5 поддерживает встроенную функцию in_array для определения, является ли элемент в массиве или нет. Но по какой-то причине я использую предварительную версию PHP и хочу знать, что для нее альтернатива.

5 ответов

Используйте специальную функцию. Для будущей совместимости вы можете использовать function_exists чтобы проверить, действительно ли текущая версия PHP, которую вы используете, имеет in_array .

function inArray($needle, $haystack) < if (function_exists('in_array')) < return in_array($needle, $haystack); >else < foreach ($haystack as $e) < if ($e === $needle) < return true; >> return false; > > 

Интересно, почему этот способ принят, потому что если нет функции in_array , также не существует цикла foreach . Оба были введены в первой версии PHP 4. Лучший ответ дал dev-null-dweller: проверьте, не доступна ли эта функция, и только затем определите ее с тем же именем, а также самые базовые элементы до тысячелетия. PHP.

Если вы используете что-то старше PHP 4, foreach также будет недоступен, поэтому вам нужно будет придерживаться list и each . Также, чтобы сделать в режиме пересылки, используйте третий параметр для строгого сравнения:

if (!function_exists('in_array')) < function in_array($needle, $haystack, $strict = false) < while (list($key, $item) = each($haystack)) < if ($strict && $needle === $item) < return true; >else if (!$strict && $needle == $item) < return true; >> return false; > > 

Источник

in_array

Ищет в haystack значение needle . Если strict не установлен, то при поиске будет использовано нестрогое сравнение.

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

Замечание:

Если needle — строка, сравнение будет произведено с учётом регистра.

Если третий параметр strict установлен в true , тогда функция in_array() также проверит соответствие типов параметра needle и соответствующего значения массива haystack .

Замечание:

До PHP 8.0.0 строковое значение параметра needle будет соответствовать значению массива 0 в нестрогом режиме, и наоборот. Это может привести к нежелательным результатам. Подобные крайние случаи существуют и для других типов. Если нет полной уверенности в типах значений, всегда используйте флаг strict , чтобы избежать неожиданного поведения.

Возвращаемые значения

Возвращает true , если needle был найден в массиве, и false в противном случае.

Примеры

Пример #1 Пример использования in_array()

$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

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

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() — Проверяет, присутствует ли в массиве указанный ключ или индекс

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

Источник

Читайте также:  Copy file post php
Оцените статью