Как найти массив в массиве php

(PHP 4, PHP 5, PHP 7, PHP 8)

in_arrayПроверяет, присутствует ли в массиве значение

Описание

in_array(mixed $needle, array $haystack, bool $strict = false): bool

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

needle

Искомое значение.

Замечание:

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

haystack

Массив.

strict

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

Замечание:

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

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

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

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)


Here’s a way I am doing it after researching it for a while. I wanted to make a Laravel API endpoint that checks if a field is “in use”, so the important information is: 1) which DB table? 2) what DB column? and 3) is there a value in that column that matches the search terms?

Knowing this, we can construct our associative array:

$SEARCHABLE_TABLE_COLUMNS = [
    'users' => [ 'email' ],
];

Then, we can set our values that we will check:

$table = 'users';
$column = 'email';
$value = 'alice@bob.com';

Then, we can use array_key_exists() and in_array() with eachother to execute a one, two step combo and then act upon the truthy condition:

// step 1: check if 'users' exists as a key in `$SEARCHABLE_TABLE_COLUMNS`
if (array_key_exists($table, $SEARCHABLE_TABLE_COLUMNS)) {

    // step 2: check if 'email' is in the array: $SEARCHABLE_TABLE_COLUMNS[$table]
    if (in_array($column, $SEARCHABLE_TABLE_COLUMNS[$table])) {

        // if table and column are allowed, return Boolean if value already exists
        // this will either return the first matching record or null
        $exists = DB::table($table)->where($column, '=', $value)->first();

        if ($exists) return response()->json([ 'in_use' => true ], 200);
        return response()->json([ 'in_use' => false ], 200);
    }

    // if $column isn't in $SEARCHABLE_TABLE_COLUMNS[$table],
    // then we need to tell the user we can't proceed with their request
    return response()->json([ 'error' => 'Illegal column name: '.$column ], 400);
}

// if $table isn't a key in $SEARCHABLE_TABLE_COLUMNS,
// then we need to tell the user we can't proceed with their request
return response()->json([ 'error' => 'Illegal table name: '.$table ], 400);

I apologize for the Laravel-specific PHP code, but I will leave it because I think you can read it as pseudo-code. The important part is the two if statements that are executed synchronously.

array_key_exists() and in_array() are PHP functions.

source:

  • https://php.net/manual/en/function.array-key-exists.php

  • https://php.net/manual/en/function.in-array.php

The nice thing about the algorithm that I showed above is that you can make a REST endpoint such as GET /in-use/{table}/{column}/{value} (where table, column, and value are variables).

You could have:

$SEARCHABLE_TABLE_COLUMNS = [
    'accounts' => [ 'account_name', 'phone', 'business_email' ],
    'users' => [ 'email' ],
];

and then you could make GET requests such as:

GET /in-use/accounts/account_name/Bob's Drywall (you may need to uri encode the last part, but usually not)

GET /in-use/accounts/phone/888-555-1337

GET /in-use/users/email/alice@bob.com

Notice also that no one can do:

GET /in-use/users/password/dogmeat1337 because password is not listed in your list of allowed columns for user.

Good luck on your journey.

next →
← prev

The in_array( ) function is an inbuilt function of PHP. It is used to search an array for a specific value. If the third parameter strict is set to true, the in_array( ) function will also check the types of the $values.

Syntax

Parameter

Parameter Description Is compulsory
value Specifies the value to be searched in the array. compulsory
array Specifies an array. compulsory
strict If this parameter is set, the in_array( ) function searches for the search-string and specific type in the array. Optional

Returns

The function returns true if the value is found in the array or false otherwise.

Example 1

Output:

found

Example 2

Output:

Got jobGot innovation

Example 3

Output:

great player

Example 4

Output:

found not found

Next TopicPHP Array Functions

← prev
next →

За последние 24 часа нас посетили 13045 программистов и 990 роботов. Сейчас ищут 826 программистов …

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.41.13);

if (

in_array('12.4'$atrue)) {
    echo 
"'12.4' найдено со строгой проверкойn";
}

if (

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

Вернуться к: Функции для работы с массивами

I have an array as follows

array(2) {
  ["operator"] => array(2) {
    ["qty"] => int(2)
    ["id"] => int(251)
  }
  ["accessory209"] => array(2) {
    ["qty"] => int(1)
    ["id"] => int(209)
  }
  ["accessory211"] => array(2) {
    ["qty"] => int(1)
    ["id"] => int(211)
  }
}

I’m trying to find a way to verify an id value exists within the array and return bool. I’m trying to figure out a quick way that doesn’t require creating a loop. Using the in_array function did not work, and I also read that it is quite slow.

In the php manual someone recommended using flip_array() and then isset(), but I can’t get it to work for a 2-d array.

doing something like

if($array['accessory']['id'] == 211)

would also work for me, but I need to match all keys containing accessory — not sure how to do that

Anyways, I’m spinning in circles, and could use some help.
This seems like it should be easy. Thanks.

asked Apr 22, 2010 at 18:14

dardub's user avatar

dardubdardub

3,1565 gold badges29 silver badges31 bronze badges

9

array_walk() can be used to check whether a particular value is within the array; – it iterates through all the array elements which are passed to the function provided as second argument. For example, the function can be called as in the following code.

function checkValue($value, $key) {
  echo $value['id'];
}

$arr = array(
  'one' => array('id' => 1),
  'two' => array('id' => 2),
  'three' => array('id' => 3)
);

array_walk($arr, 'checkValue');

apaderno's user avatar

apaderno

28.3k16 gold badges75 silver badges90 bronze badges

answered Apr 22, 2010 at 18:32

falomir's user avatar

falomirfalomir

1,1591 gold badge9 silver badges16 bronze badges

4

This function is useful in_array(211, $array['accessory']); It verifies the whole specified array to see if your value exists in there and returns true.

in_array

Community's user avatar

answered Apr 22, 2010 at 18:39

Jonathan Czitkovics's user avatar

$map = array();
foreach ($arr as $v) {
    $map[$v['id']] = 1;
}
//then you can just do this as when needed
$exists = isset($map[211]);

Or if you need the data associated with it

$map = array();
foreach ($arr as $k => $v) {
    $map[$v['id']][$k] = $v;
}
print_r($map[211]);

answered Apr 22, 2010 at 21:47

goat's user avatar

goatgoat

31.2k7 gold badges72 silver badges96 bronze badges

<?php

//PHP 5.3 way to do it

function searchNestedArray(array $array, $search, $mode = 'value') {

    foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $key => $value) {
        if ($search === ${${"mode"}})
            return true;
    }
    return false;
}

$data = array(
    array('abc', 'ddd'),
    'ccc',
    'bbb',
    array('aaa', array('yyy', 'mp' => 555))
);

var_dump(searchNestedArray($data, 555));

answered Mar 25, 2011 at 1:40

Pramendra Gupta's user avatar

Pramendra GuptaPramendra Gupta

14.5k4 gold badges33 silver badges34 bronze badges

I used a static method because i needed it in a class, but if you want you can use it as a simple function.

/**
 * Given an array like this
 * array(
 *   'id' => "first",
 *   'title' => "First Toolbar",
 *   'class' => "col-md-12",
 *   'items' => array(
 *       array(
 *           'tipo' => "clientLink",
 *           'id' => "clientLinkInsert"
 *       )
 *   )
 * )
 *
 * and array search like this
 * array("items", 0, "id")
 * 
 * Find the path described by the array search, in the original array
 *
 * @param array $array source array
 * @param array $search the path to the item es. ["items", 0, "tipo"]
 * @param null|mixed $defaultIfNotFound the default value if the value is not found
 *
 * @return mixed
 */
public static function getNestedKey($array, $search, $defaultIfNotFound = null)
{
    if( count($search) == 0 ) return $defaultIfNotFound;
    else{
        $firstElementSearch = self::array_kshift($search);

        if (array_key_exists($firstElementSearch, $array)) {
            if( count($search) == 0 )
                return $array[$firstElementSearch];
            else
                return self::getNestedKey($array[$firstElementSearch], $search, $defaultIfNotFound);
        }else{
            return $defaultIfNotFound;
        }
    }
}

answered Aug 3, 2017 at 11:27

David Ginanni's user avatar

You can use

Arr::getNestedElement($array, $keys, $default = null)

from this library to get value from multidimensional array using keys specified like 'key1.key2.key3' or ['key1', 'key2', 'key3'] and fallback to default value if no element was found. Using your example it will look like:

if (Arr::getNestedElement($array, 'accessory.id') == 211)

answered Sep 5, 2018 at 23:05

Minwork's user avatar

MinworkMinwork

7907 silver badges9 bronze badges

Добавить комментарий