2

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;
}
8
  • Do you mean array_search()? Please set up a php sample. There may be more than one way to do it and it depending on your data structure and values, one way may be better than another. Commented Feb 19, 2018 at 13:13
  • 1
    php.net/manual/en/function.array-filter.php Commented Feb 19, 2018 at 13:15
  • PHP has different structures than Javascript, like associative arrays. There is nothing exactly like findIndex built into PHP, but several functions that can produce similar results depending on your use case. Commented Feb 19, 2018 at 13:17
  • There's no native function in PHP to do this. Using array_filter and then grabbing the first key from the result will do what you want, but that might not be performant depending on the size of your array. Commented Feb 19, 2018 at 13:17
  • array_search combined with array_column then. Commented Feb 19, 2018 at 13:18

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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;

Comments

0
current(array_filter($array, function($e){return $e->property_you_want_to_lookup == 'value you are looking for';}));

in your case

current(array_filter($library, function($e) use ($name){return $e->name == $name;}));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.