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

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

array_searchSearches the array for a given value and returns the first corresponding key if successful

Description

array_search(mixed $needle, array $haystack, bool $strict = false): int|string|false

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

Warning

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


<?php
$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

turabgarip at gmail dot com

6 years ago


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.

<?php array_search($needle, array_column($array, 'key')); ?>

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.

For example;

<?php
$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;

<?php
$colors
= array_column($people, 'fav_color');
$found_key = array_search('blue', $colors);
?>


cue at openxbox dot com

19 years ago


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:

<?php

$code
= array("a", "b", "a", "c", "a", "b", "b"); // infamous abacabb mortal kombat code :-P

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

}

?>


stefano@takys dot it

12 years ago


for searching case insensitive better this:

<?php

array_search
(strtolower($element),array_map('strtolower',$array));

?>


RichGC

17 years ago


To expand on previous comments, here are some examples of
where using array_search within an IF statement can go
wrong when you want to use the array key thats returned.

Take the following two arrays you wish to search:

<?php
$fruit_array
= array("apple", "pear", "orange");
$fruit_array = array("a" => "apple", "b" => "pear", "c" => "orange");

if (

$i = array_search("apple", $fruit_array))
//PROBLEM: the first array returns a key of 0 and IF treats it as FALSEif (is_numeric($i = array_search("apple", $fruit_array)))
//PROBLEM: works on numeric keys of the first array but fails on the secondif ($i = is_numeric(array_search("apple", $fruit_array)))
//PROBLEM: using the above in the wrong order causes $i to always equal 1if ($i = array_search("apple", $fruit_array) !== FALSE)
//PROBLEM: explicit with no extra brackets causes $i to always equal 1if (($i = array_search("apple", $fruit_array)) !== FALSE)
//YES: works on both arrays returning their keys
?>


thinbegin at gmail dot com

5 years ago


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;
}

usage example:
-------------------

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

$search_value = 'insane';

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

var_dump($array_keymap);
// Outputs:
// array(3) {
// [0]=>
//  string(1) "b"
//  [1]=>
//  string(5) "three"
//  [2]=>
//  string(3) "iii"
//}

----------------------------------------------

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]];
    }

    return $value;
}

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


opencart dot ocfilter at gmail dot com

1 year ago


Be careful!

<?php

var_dump

(array_search('needle', [ 0 => 0 ])); // int(0) (!)var_dump(array_search('needle', [ 0 => 0 ], true)); // bool(false)?>

But, in php 8

<?php

var_dump

(array_search('needle', [ 0 => 0 ])); // bool(false)?>


maciej at speccode dot com

7 years ago


FYI, remember that strict mode is something that might save you hours.

If you're searching for a string and you have a "true" boolean on the way - you will get it as result (first occurrence). Example below:

<?php

$arr

= [
   
'foo'    => 'bar',
   
'abc'    => 'def',
   
'bool'   => true,
   
'target' => 'xyz'
];var_dump( array_search( 'xyz', $arr ) ); //bool
var_dump( array_search( 'xyz', $arr, true ) ); //target?>


azaozz, gmail

14 years ago


Expanding on the comment by hansen{}cointel.de:

When searching for a string and the array contains 0 (zero), the string is casted to (int) by the type-casting which is always 0 (perhaps the opposite is the proper behaviour, the array value 0 should have been casted to string). That produces unexpected results if strict comparison is not used:

<?php
$a
= array(0, "str1", "str2", "str3");
echo
"
str1 = "
.array_search("str1", $a).",
str2 = "
.array_search("str2", $a).",
str3 = "
.array_search("str3", $a).",

str1 strict = "

.array_search("str1", $a, true).",
str2 strict = "
.array_search("str2", $a, true).",
str3 strict = "
.array_search("str3", $a, true);
?>

This will return:
str1 = 0, str2 = 0, str3 = 0, str1 strict = 1, str2 strict = 2, str3 strict = 3


codeslinger at compsalot dot com

13 years ago


one thing to be very aware of is that array_search() will fail if the needle is a string and the array itself contains values that are mixture of numbers and strings.  (or even a string that looks like a number)

The problem is that unless you specify "strict" the match is done using ==    and in that case any string will match a numeric value of zero which is not what you want.

-----

also, php can lookup an index pretty darn fast.  for many scenarios, it is practical to maintain multiple arrays, one in which the index of the array is the search key and the normal array that contains the data.

<?php

  $normal

[$index] = array('key'=>$key, 'data'=>'foo');

 
$inverse[$key] = $index;
//very fast lookup, this beats any other kind of search
if (array_key_exists($key, $inverse))

  {

   
$index = $inverse[$key];

    return
$normal[$index];

  }
?>


n-regen

14 years ago


If you only know a part of a value in an array and want to know the complete value, you can use the following function:
<?php
function array_find($needle, $haystack)
{
   foreach (
$haystack as $item)
   {
      if (
strpos($item, $needle) !== FALSE)
      {
         return
$item;
         break;
      }
   }
}
?>
The function returns the complete first value of $haystack that contains $needle.

andreas dot damm at maxmachine dot de

15 years ago


Combining syntax of array_search() and functionality of array_keys() to get all key=>value associations of an array with the given search-value:
<?php
function array_search_values( $m_needle, $a_haystack, $b_strict = false){
    return
array_intersect_key( $a_haystack, array_flip( array_keys( $a_haystack, $m_needle, $b_strict)));
}
?>

Usage:
<?php
$array1
= array( 'pre'=>'2', 1, 2, 3, '1', '2', '3', 'post'=>2);
print_r( array_search_values( '2', $array1));
print_r( array_search_values( '2', $array1, true));
print_r( array_search_values( 2, $array1, true));
?>

Will return:
array(4) {
    ["pre"] =>
    string(1) "2"
    [1] =>
    int(2)
    [4] =>
    string(1) "2"
    ["post"] =>
    int(2)
}
array(2) {
    ["pre"] =>
    string(1) "2"
    [4] =>
    string(1) "2"
}
array(2) {
    [1] =>
    int(2)
    ["post"] =>
    int(2)
}

yasien dot dwieb at gmail dot com

3 years ago


Beware when using array_search to a mix of string and integer where prefixes of keys may collide, as in my case I have encountered the following situation:

Assume you have the following array:
<?php
$arr
= [
          
1 => 'index 0',
          
2 => 'index 1',
          
3 => 'index 2',
          
'3anothersuffix' => 'index 3'
];$index1 = array_search('3', array_keys($arr)); // 2
$index2 = array_search('3anothersuffix', array_keys($arr)); //2
?>

$index1 and $index2 will be the same

after using strict type search:

<?php
$index1
= array_search('3', array_keys($arr), true); // false
$index2 = array_search('3anothersuffix', array_keys($arr), true);  //3
?>

it will not find $index1 at all while returning a correct value for $index2;


stooshie at gmail dot com

11 years ago


Example of a recursive binary search that returns the index rather than boolean.
<?php
// returns the index of needle in haystack
function binSearch($needle, $haystack)
{
   
// n is only needed if counting depth of search
   
global $n;
   
$n++;
   
// get the length of passed array
   
$l = count($haystack);
   
// if length is 0, problem
   
if($l <= 0)
    {
        return -
1;
    }
   
// get the mid element
   
$m = (($l+($l%2))/2);
   
// if mid >= length (e.g. l=1)
   
if($m >= $l)
    {
       
$m = $m-1;
    }
   
// get the indexed element to compare to the passed element and branch accordingly
   
$compare = $haystack[$m];
    switch(
true)
    {
        case(
$compare>$needle):
        {
           
// recurse on the lower half
           
$new_haystack = array_slice($haystack, 0, $m);
           
$c = count($new_haystack);
           
$r = binSearch($needle, $new_haystack);
           
// return current index - (length of lower half - found index in lower half)
           
return $m - ($c - $r);
            break;
        }
        case(
$compare<$needle):
        {
           
// recurse on the upper half
           
$new_haystack = array_slice($haystack, $m, ($l-$m));
           
$c = count($new_haystack);
           
$r = binSearch($needle, $new_haystack);
           
// return current position + found index in upper half
           
return $m + $r;
            break;
        }
        case(
$compare==$needle):
        {
           
// found it, so return index
           
return $m;
            break;
        }
    }
}
?>

helenadeus at gmail dot com

14 years ago


I was trying to use array_search to retrieve all the values that match a given needle, but it turns out only the first match key is returned. I built this little function, which works just like array_search, but returns all the keys that match a given needle instead. The output is an array.

<?php

$haystack

= array('a','b','a','b');$needle = 'a';print_r(array_search_all($needle, $haystack));//Output will be
// Array
// (
//         [0]=>1
//         [1]=>3
// )
function array_search_all($needle, $haystack)
{
#array_search_match($needle, $haystack) returns all the keys of the values that match $needle in $haystackforeach ($haystack as $k=>$v) {

            if(

$haystack[$k]==$needle){$array[] = $k;
        }
    }
    return (
$array);

    }

?>


nordseebaer at gmx dot de

3 years ago


It's really important to check the return value is not false! I used array_search() to determine the index of an value to unset this value and then realized that $arr[false] === $arr[0] !

<?php
$arr
= ['apple', 'banana'];var_dump($arr[0] === 'apple'); // true
var_dump($arr[false] === $arr[0]); // true
var_dump($arr[false] === 'apple'); // trueunset($arr[array_search('banana', $arr)]); //index = 1
var_dump($arr);// result
//   array(1) {
//     [0]=>
//     string(5) "apple"
//   }
unset($arr[array_search('peach', $arr)]); //not found, result is false
var_dump($arr);// result
//   array(0) {
//   }
// because $arr[false] === $arr[0]
?>

So always check the return of array_search!


kermes [at] thesevens [dot] net

15 years ago


A variation of previous searches that returns an array of keys that match the given value:

<?php
function array_ksearch($array, $str)
{
   
$result = array();
    for(
$i = 0; $i < count($array); next($array), $i++)
        if(
strtolower(current($array)) == strtolower($str))
           
array_push($result, key($array);

        return

$result;
}
?>

Usage would be as follows:
<?php
$testArray
= array('one' => 'test1', 'two' => 'test2', 'three' => 'test1', 'four' => 'test2', 'five' => 'test1');
   
print_r(array_ksearch($testArray, 'test1'));
?>


The array looks like:

[0] => stdClass Object
        (
            [ID] => 420
            [name] => Mary
         )

[1] => stdClass Object
        (
            [ID] => 10957
            [name] => Blah
         )
...

And I have an integer variable called $v.

How could I select an array entry that has an object where the ID property has the $v value?

Dharman's user avatar

Dharman

30.3k22 gold badges84 silver badges132 bronze badges

asked Jan 20, 2011 at 2:24

Alex's user avatar

You either iterate the array, searching for the particular record (ok in a one time only search) or build a hashmap using another associative array.

For the former, something like this

$item = null;
foreach($array as $struct) {
    if ($v == $struct->ID) {
        $item = $struct;
        break;
    }
}

See this question and subsequent answers for more information on the latter – Reference PHP array by multiple indexes

Community's user avatar

answered Jan 20, 2011 at 2:27

Phil's user avatar

PhilPhil

155k23 gold badges240 silver badges242 bronze badges

3

$arr = [
  [
    'ID' => 1
  ]
];

echo array_search(1, array_column($arr, 'ID')); // prints 0 (!== false)

Above code echoes the index of the matching element, or false if none.

To get the corresponding element, do something like:

$i = array_search(1, array_column($arr, 'ID'));
$element = ($i !== false ? $arr[$i] : null);

array_column works both on an array of arrays, and on an array of objects.

ToolmakerSteve's user avatar

answered Mar 27, 2017 at 11:14

Tim's user avatar

TimTim

2,1661 gold badge18 silver badges25 bronze badges

10

YurkamTim is right. It needs only a modification:

After function($) you need a pointer to the external variable by “use(&$searchedValue)” and then you can access the external variable. Also you can modify it.

$neededObject = array_filter(
    $arrayOfObjects,
    function ($e) use (&$searchedValue) {
        return $e->id == $searchedValue;
    }
);

Jean-François Fabre's user avatar

answered Oct 22, 2013 at 13:36

Daniel Hardt's user avatar

5

I’ve found more elegant solution here. Adapted to the question it may look like:

$neededObject = array_filter(
    $arrayOfObjects,
    function ($e) use ($searchedValue) {
        return $e->id == $searchedValue;
    }
);

AndreyP's user avatar

AndreyP

2,4901 gold badge28 silver badges17 bronze badges

answered Jul 17, 2013 at 8:27

YurkaTim's user avatar

YurkaTimYurkaTim

6815 silver badges7 bronze badges

6

Using array_column to re-index will save time if you need to find multiple times:

$lookup = array_column($arr, NULL, 'id');   // re-index by 'id'

Then you can simply $lookup[$id] at will.

answered May 24, 2017 at 20:29

Museful's user avatar

MusefulMuseful

6,6814 gold badges40 silver badges68 bronze badges

0

Try

$entry = current(array_filter($array, function($e) use($v){ return $e->ID==$v; }));

working example here

answered Mar 13, 2019 at 22:12

Kamil Kiełczewski's user avatar

Kamil KiełczewskiKamil Kiełczewski

83k29 gold badges358 silver badges335 bronze badges

2

class ArrayUtils
{
    public static function objArraySearch($array, $index, $value)
    {
        foreach($array as $arrayInf) {
            if($arrayInf->{$index} == $value) {
                return $arrayInf;
            }
        }
        return null;
    }
}

Using it the way you wanted would be something like:

ArrayUtils::objArraySearch($array,'ID',$v);

answered Mar 10, 2015 at 17:24

Pablo S G Pacheco's user avatar

0

Fixing a small mistake of the @YurkaTim, your solution work for me but adding use:

To use $searchedValue, inside of the function, one solution can be use ($searchedValue) after function parameters function ($e) HERE.

the array_filter function only return on $neededObject the if the condition on return is true

If $searchedValue is a string or integer:

$searchedValue = 123456; // Value to search.
$neededObject = array_filter(
    $arrayOfObjects,
    function ($e) use ($searchedValue) {
        return $e->id == $searchedValue;
    }
);
var_dump($neededObject); // To see the output

If $searchedValue is array where we need check with a list:

$searchedValue = array( 1, 5 ); // Value to search.
$neededObject  = array_filter(
    $arrayOfObjects,
    function ( $e ) use ( $searchedValue ) {
        return in_array( $e->term_id, $searchedValue );
    }
);
var_dump($neededObject); // To see the output

answered Apr 8, 2017 at 18:45

Jose Carlos Ramos Carmenates's user avatar

1

I sometimes like using the array_reduce() function to carry out the search. It’s similar to array_filter() but does not affect the searched array, allowing you to carry out multiple searches on the same array of objects.

$haystack = array($obj1, $obj2, ...); //some array of objects
$needle = 'looking for me?'; //the value of the object's property we want to find

//carry out the search
$search_results_array = array_reduce(
  $haystack,

  function($result_array, $current_item) use ($needle){
      //Found the an object that meets criteria? Add it to the the result array 
      if ($current_item->someProperty == $needle){
          $result_array[] = $current_item;
      }
      return $result_array;
  },
  array() //initially the array is empty (i.e.: item not found)
);

//report whether objects found
if (count($search_results_array) > 0){
  echo "found object(s): ";
  print_r($search_results_array[0]); //sample object found
} else {
  echo "did not find object(s): ";
}

answered Feb 10, 2016 at 18:10

yuvilio's user avatar

yuvilioyuvilio

3,67532 silver badges34 bronze badges

3

Way to instantly get first value:

$neededObject = array_reduce(
    $arrayOfObjects,
    function ($result, $item) use ($searchedValue) {
        return $item->id == $searchedValue ? $item : $result;
    }
);

answered Apr 4, 2019 at 12:14

AndreyP's user avatar

AndreyPAndreyP

2,4901 gold badge28 silver badges17 bronze badges

I did this with some sort of Java keymap.
If you do that, you do not need to loop over your objects array every time.

<?php

//This is your array with objects
$object1 = (object) array('id'=>123,'name'=>'Henk','age'=>65);
$object2 = (object) array('id'=>273,'name'=>'Koos','age'=>25);
$object3 = (object) array('id'=>685,'name'=>'Bram','age'=>75);
$firstArray = Array($object1,$object2);
var_dump($firstArray);

//create a new array
$secondArray = Array();
//loop over all objects
foreach($firstArray as $value){
    //fill second        key          value
    $secondArray[$value->id] = $value->name;
}

var_dump($secondArray);

echo $secondArray['123'];

output:

array (size=2)
  0 => 
    object(stdClass)[1]
      public 'id' => int 123
      public 'name' => string 'Henk' (length=4)
      public 'age' => int 65
  1 => 
    object(stdClass)[2]
      public 'id' => int 273
      public 'name' => string 'Koos' (length=4)
      public 'age' => int 25
array (size=2)
  123 => string 'Henk' (length=4)
  273 => string 'Koos' (length=4)
Henk

answered Jan 7, 2016 at 10:03

Mart-Jan's user avatar

2

I solved this problem by keying the array with the ID. It’s simpler and possibly faster for this scenario where the ID is what you’re looking for.

[420] => stdClass Object
        (
            [name] => Mary
         )

[10957] => stdClass Object
        (
            [name] => Blah
         )
...

Now I can directly address the array:

$array[$v]->name = ...

Or, if I want to verify the existence of an ID:

if (array_key_exists($v, $array)) { ...

answered Oct 29, 2020 at 15:55

Chad E.'s user avatar

Chad E.Chad E.

1,1969 silver badges12 bronze badges

3

      $keyToLookFor = $term->name;
      $foundField = array_filter($categories, function($field) use($keyToLookFor){
      return $field -> name === $keyToLookFor; });

      if(!empty($foundField)){
      $ke = array_keys($foundField);
      $ke = $ke[0];
      $v = $foundField[$ke]->id;}

Am Working On WordPress Theme Get Total Comment from Catagories And This help me out for Arrays

answered Apr 29, 2022 at 14:07

amosu dona's user avatar

array_search

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

array_searchОсуществляет поиск данного значения в массиве и возвращает
соответствующий ключ в случае удачи

Описание

mixed array_search
( mixed $needle
, array $haystack
[, bool $strict = false
] )

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

needle

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

Замечание:

Если needle является строкой, сравнение
происходит с учетом регистра.

haystack

Массив.

strict

Если третий параметр strict установлен в
TRUE, то функция array_search() будет искать
идентичные элементы в haystack.
Это означает, что также будут проверяться
типы
needle в haystack,
а объекты должны быть одни и тем же экземпляром.

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

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

Если needle присутствует в
haystack более одного раза, будет возвращён
первый найденный ключ. Для того, чтобы возвратить ключи для всех
найденных значений, используйте функцию array_keys()
с необязательным параметром search_value.

Внимание

Эта функция
может возвращать как boolean FALSE, так и не-boolean значение,
которое приводится к FALSE. За более подробной информацией обратитесь к разделу
Булев тип. Используйте оператор === для проверки значения,
возвращаемого этой функцией.

Список изменений

Версия Описание
5.3.0 Вместе со всеми внутренними функциями PHP начиная с 5.3.0,
array_search() возвращает NULL, если
ей были переданы неверные параметры.
4.2.0 До PHP 4.2.0, array_search() при неудаче
возвращал NULL вместо FALSE.

Примеры

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


<?php
$array 
= array(=> 'blue'=> 'red'=> 'green'=> 'red');$key array_search('green'$array); // $key = 2;
$key array_search('red'$array);   // $key = 1;
?>

Смотрите также

  • array_keys() – Возвращает все или некоторое подмножество ключей массива
  • array_values() – Выбирает все значения массива
  • array_key_exists() – Проверяет, присутствует ли в массиве указанный ключ или индекс
  • in_array() – Проверяет, присутствует ли в массиве значение

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

PHP array_search() Function

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    In this article, we will see how to search the specific value in an array & corresponding return the key using the array_search() function in PHP, & will also understand its implementation through the examples. The array_search() is an inbuilt function in PHP that is used to search for a particular value in an array, and if the value is found then it returns its corresponding key. If there are more than one values then the key of the first matching value will be returned.

    Syntax:

    array_search($value, $array, strict_parameter)

    Parameters: This function takes three parameters as described below:

    • $value: This is the mandatory field that refers to the value that needs to be searched in the array.
    • $array: This is the mandatory field that refers to the original array, which needs to be searched.
    • strict_parameter (optional): This is an optional field that can be set to TRUE or FALSE, and refers to the strictness of search. The default value of this parameter is FALSE. 
      • If TRUE, then the function checks for identical elements, i.e., an integer 10 will be treated differently from a string 10.
      • If FALSE, strictness is not maintained.

    Return Value: The function returns the key of the corresponding value that is passed. If not found then FALSE is returned and if there is more than one match, then the first matched key is returned.

    Example: The below program illustrates the array_search() function in PHP.

    <?php

      function Search($value, $array)

      {

          return (array_search($value, $array));

      }

      $array = array(

          "ram",

          "aakash",

          "saran",

          "mohan",

          "saran"

      );

      $value = "saran";

      print_r(Search($value, $array));

    ?>

    Output:

    2

    Example: This example illustrates the working of function when the strict_parameter is set to FALSE. Note that the data types of the array and to be searched elements are different. 

    PHP

    <?php

        function Search($value, $array)

        {

            return (array_search($value, $array, false));

        }

        $array = array(

            45, 5, 1, 22, 22, 10, 10);

        $value = "10";

        print_r(Search($value, $array));

    ?>

    Output:

    5

    Example: In this example, we will be utilizing the above code to find out what will happen if we pass the strict_parameter as TRUE.

    PHP

    <?php

        function Search($value, $array)

        {

            return (array_search($value, $array, true));

        }

        $array = array(45, 5, 1, 22, 22, 10, 10);

        $value = "10";

        print_r(Search($value, $array));

    ?>

    Output:

    No Output

    Reference: http://php.net/manual/en/function.array-search.php

    Last Updated :
    01 Dec, 2021

    Like Article

    Save Article

    The array_search function searches the specified value in the array and returns its key. If the array is an indexed array, you will get the index of the value found.

    What is the syntax of the array_search function in PHP?

    array_search(value, array, strict)
    
    Parameters Details
    value The array to search the value in – Required
    array The value to search from the array – Required
    strict Boolean Parameter
    When set to true: Will does not search the identical elements, that is “5” and 5 will not be considered to be similar.
    When set to false: Will search the identical elements, that is “5” and 5 will be considered to be similar.
    – Optional
    array_search function in PHP

    Examples of array_search function

    <?php
    $arr=array("a"=>"Pakistan","b"=>"Iran","c"=>"Turkey");
    echo array_search("Turkey",$arr);
    ?>

    In the above example, we use array_search to search “Turkey” from the given array.

    <?php
    $arr=array("a"=>"1","b"=>1,"c"=>"1");
    echo array_search(5,$arr,true);
    ?>

    In the above example, we use array_search to search the specified element from the associative array with a strict mode set to true. Try the above example with strict mode set to false.

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