简体   繁体   中英

equivalent of JavaScript findIndex() in PHP

This is how I am retrieving items from an array in JavaScript, it works fine:

function getLibItemByName(name){
    var index = json.library.findIndex(p => p.name == name);
    return json.library[index];
}

my array is like:

[
    {
        "name": "item1"
    },
    {
        "name": "item2"
    },
    ...
]

Now I am wondering how I can do the same in PHP?

Update : I came up with this that is working for now

function getLibItemByName($name){
    global $json;
    foreach($json['library'] as $key => $val){
        if($name === $val['name']){
            return $json['library'][$key];
        }
    }
    return false;
}

Use array_search() function, it works like this:

array_search(what_to_search,array_variable,true/false);

FALSE is default parameter. If this parameter is set to TRUE, then this function will search for identical elements in the array. When set to true, the number 5 is not the same as the string 5.

Here is the given example:

$a=array("a"=>"5","b"=>5,"c"=>"5");
echo array_search(5,$a,true);

Returns the key of a value if it is found in the array, and FALSE otherwise. If the value is found in the array more than once, the first matching key is returned.

In PHP, there is an array function array_serach() which matches value and returns of its key. It takes search value as an first argument and array as an second argument.

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

    $key = array_search('green', $array); // $key = 2;
    $key = array_search('red', $array);   // $key = 1;

I'll offer two suggestions.

  1. A few adjustments on your foreach loop method.
  2. A combination of array_search() and array_column()

A few explanations via inline comments.

Code: ( Demo )

function getLibItemByName($array,$name){  // avoid global, assign $array as parameter
    foreach($array['library'] as $key => $row){
        if($name === $row['name']){
            return $row;  // return the whole subarray (this is a simpler expression)
        }
    }
    return false;
}

// logically rename json to array
$array=[
    'library'=>
        [
            ['name'=>'Alan','age'=>5],
            ['name'=>'Bert','age'=>6],
            ['name'=>'Chad','age'=>7],
            ['name'=>'Doug','age'=>8],
            ['name'=>'Eddy','age'=>9],
            ['name'=>'Fred','age'=>10]
        ]
];

var_export(getLibItemByName($array,'Chad'));
echo "\n---\n";
var_export(getLibItemByName($array,'Greg'));

echo "\n---\n";

if(($index=array_search('Eddy',array_column($array['library'],'name')))!==false){
    var_export($array['library'][$index]);
}else{
    echo 'No match';
}

Output:

array (
  'name' => 'Chad',
  'age' => 7,
)
---
false
---
array (
  'name' => 'Eddy',
  'age' => 9,
)
current(array_filter($array, function($e){return $e->property_you_want_to_lookup == 'value you are looking for';}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM