I come from a Javascript background, and I am trying to use array_filter()
, but it works quite different from JS.
Taking this JS example:
const people = [
{
name: 'Will',
username: 'will',
},
{
name: 'Alex',
username: 'alex',
},
{
name: 'Abraham',
username: 'abraham',
},
];
const usernameToFind = 'abraham';
const found = people.filter(person => person.username === usernameToFind);
console.log(found[0]); // index 0
// {
// name: 'Abraham',
// username: 'abraham'
// }
I expect all the usernames to be different, so it is always going to return only one value. So if I want to access the information found I just ask for index 0
.
On PHP:
<?php
$people = [
[
'name' => 'Alex',
'username' => 'alex',
],
[
'name' => 'Will',
'username' => 'will',
],
[
'name' => 'Abraham',
'username' => 'abraham',
],
];
$usernameToFind = 'abraham';
$found = array_filter($people, function($person) use ($usernameToFind) {
return $person['username'] === $usernameToFind;
});
print_r($found);
// Array
// (
// [2] => Array
// (
// [name] => Abraham
// [username] => abraham
// )
// )
So my issue is: I get an array with the index of the element found, but I don't know what the index is.
I saw this question but it is quite different: PHP array_filter to get only one value from an array.
I am not using array_search()
, because my needle to search is 2 or 3 levels deep like:
array_filter($people, function ($person) use ($cityToFind) {
return $person['location']['city'] === $cityToFind;
}
I can use a for loop, but I really wanted to use filter instead. Thanks in advance!