Php find var in array

Как сделать поиск в php массиве по значению

Можно использовать встроенную функцию array_search() , она возвращает ключ найденного элемента. Затем мы можем получить и сам элемент по этому ключу.

 $numbers = [1, 2, 'salad', 'potato']; $potatoIndex = array_search('potato', $numbers); // 3 print_r($numbers[$potatoIndex]); //=> potato 

Поиск значения с помощью цикла foreach() .

Если значение подразумевает не полное соответствие, а частичное, то применяют обычно цикл с проверкой на вхождение искомого значения в значениях массива:

 $array = [ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', ]; $result = ''; foreach ($array as $value)  if (str_contains($value, '5'))  $result = $value; > > echo($result); // => value5 

Источник

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

Источник

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 array_search() function will search for identical elements in the haystack . This means it will also perform a strict type comparison of the needle in the haystack , and objects must be the same instance.

Return Values

Returns the key for needle if it is found in the array, false otherwise.

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.

This function may return Boolean false , but may also return a non-Boolean value which evaluates to false . Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 array_search() example

$array = array( 0 => ‘blue’ , 1 => ‘red’ , 2 => ‘green’ , 3 => ‘red’ );

$key = array_search ( ‘green’ , $array ); // $key = 2;
$key = array_search ( ‘red’ , $array ); // $key = 1;
?>

See Also

  • array_keys() — Return all the keys or a subset of the keys of an array
  • array_values() — Return all the values of an array
  • array_key_exists() — Checks if the given key or index exists in the array
  • in_array() — Checks if a value exists in an array

User Contributed Notes 16 notes

About searcing in multi-dimentional arrays; two notes on «xfoxawy at gmail dot com»;

It perfectly searches through multi-dimentional arrays combined with array_column() (min php 5.5.0) but it may not return the values you’d expect.

Since array_column() will produce a resulting array; it won’t preserve your multi-dimentional array’s keys. So if you check against your keys, it will fail.

$people = array(
2 => array(
‘name’ => ‘John’ ,
‘fav_color’ => ‘green’
),
5 => array(
‘name’ => ‘Samuel’ ,
‘fav_color’ => ‘blue’
)
);

$found_key = array_search ( ‘blue’ , array_column ( $people , ‘fav_color’ ));
?>

Here, you could expect that the $found_key would be «5» but it’s NOT. It will be 1. Since it’s the second element of the produced array by the array_column() function.

Secondly, if your array is big, I would recommend you to first assign a new variable so that it wouldn’t call array_column() for each element it searches. For a better performance, you could do;

$colors = array_column ( $people , ‘fav_color’ );
$found_key = array_search ( ‘blue’ , $colors );
?>

If you are using the result of array_search in a condition statement, make sure you use the === operator instead of == to test whether or not it found a match. Otherwise, searching through an array with numeric indicies will result in index 0 always getting evaluated as false/null. This nuance cost me a lot of time and sanity, so I hope this helps someone. In case you don’t know what I’m talking about, here’s an example:

$code = array( «a» , «b» , «a» , «c» , «a» , «b» , «b» ); // infamous abacabb mortal kombat code 😛

// this is WRONG
while (( $key = array_search ( «a» , $code )) != NULL )
<
// infinite loop, regardless of the unset
unset( $code [ $key ]);
>

// this is _RIGHT_
while (( $key = array_search ( «a» , $code )) !== NULL )
<
// loop will terminate
unset( $code [ $key ]);
>
?>

for searching case insensitive better this:

array_search ( strtolower ( $element ), array_map ( ‘strtolower’ , $array ));
?>

var_dump ( array_search ( ‘needle’ , [ 0 => 0 ])); // int(0) (!)

var_dump ( array_search ( ‘needle’ , [ 0 => 0 ], true )); // bool(false)

var_dump ( array_search ( ‘needle’ , [ 0 => 0 ])); // bool(false)

Despite PHP’s amazing assortment of array functions and juggling maneuvers, I found myself needing a way to get the FULL array key mapping to a specific value. This function does that, and returns an array of the appropriate keys to get to said (first) value occurrence.

function array_recursive_search_key_map($needle, $haystack) foreach($haystack as $first_level_key=>$value) if ($needle === $value) return array($first_level_key);
> elseif (is_array($value)) $callback = array_recursive_search_key_map($needle, $value);
if ($callback) return array_merge(array($first_level_key), $callback);
>
>
>
return false;
>

$nested_array = $sample_array = array(
‘a’ => array(
‘one’ => array (‘aaa’ => ‘apple’, ‘bbb’ => ‘berry’, ‘ccc’ => ‘cantalope’),
‘two’ => array (‘ddd’ => ‘dog’, ‘eee’ => ‘elephant’, ‘fff’ => ‘fox’)
),
‘b’ => array(
‘three’ => array (‘ggg’ => ‘glad’, ‘hhh’ => ‘happy’, ‘iii’ => ‘insane’),
‘four’ => array (‘jjj’ => ‘jim’, ‘kkk’ => ‘kim’, ‘lll’ => ‘liam’)
),
‘c’ => array(
‘five’ => array (‘mmm’ => ‘mow’, ‘nnn’ => ‘no’, ‘ooo’ => ‘ohh’),
‘six’ => array (‘ppp’ => ‘pidgeon’, ‘qqq’ => ‘quail’, ‘rrr’ => ‘rooster’)
)
);

$array_keymap = array_recursive_search_key_map($search_value, $nested_array);

But again, with the above solution, PHP again falls short on how to dynamically access a specific element’s value within the nested array. For that, I wrote a 2nd function to pull the value that was mapped above.

function array_get_nested_value($keymap, $array)
$nest_depth = sizeof($keymap);
$value = $array;
for ($i = 0; $i < $nest_depth; $i++) $value = $value[$keymap[$i]];
>

usage example:
——————-
echo array_get_nested_value($array_keymap, $nested_array); // insane

Источник

Читайте также:  Изменить размер блока css
Оцените статью