http://php.net/manual/en/function.array-search.php allows me to find the first array key based on an array value.
Can this be accomplished with a single PHP function if the value is nested in an object in the array values, or must it be manually performed as I show below?
Thank you
<?php
function getKeyBasedOnName($arr,$name)
{
foreach($arr as $key=>$o) {
if($o->name==$name) return $key;
}
return false;
}
$json='[
{
"name": "zero",
"data": [107, 31, 635, 203, 2]
},
{
"name": "one",
"data": [133, 156, 947, 408, 6]
},
{"name": "two",
"data": [1052, 954, 4250, 740, 38]
}
]';
$arr=json_decode($json);
var_dump(getKeyBasedOnName($arr,'zero')); //Return 0
var_dump(getKeyBasedOnName($arr,'one')); //Return 1
var_dump(getKeyBasedOnName($arr,'two')); //Return 2
var_dump(getKeyBasedOnName($arr,'three')); //Return false
Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.
The main difference between both the functions is that array_search() usually returns either key or index whereas in_array() returns TRUE or FALSE according to match found in search. Value: It specifies the value that needs to be searched in an array.
The count() function returns the number of elements in an array.
If you have a value and want to find the key, use array_search() like this: $arr = array ('first' => 'a', 'second' => 'b', ); $key = array_search ('a', $arr); $key will now contain the key for value 'a' (that is, 'first' ).
Just for fun, if the array is 0
based and sequential keys:
echo array_search('zero', array_column(json_decode($json, true), 'name'));
name
key values into a single arrayThis decodes the JSON into an array. You can decode it to an object after if you need that. As of PHP 7 you can use an array of objects:
echo array_search('zero', array_column(json_decode($json), 'name'));
There's no single built-in function that provides for arbitrary comparison. You can, however, roll your own generic array search:
function array_usearch(array $array, callable $comparitor) {
return array_filter(
$array,
function ($element) use ($comparitor) {
if ($comparitor($element)) {
return $element;
}
}
);
}
This has the benefit of returning an array of matches to the comparison function, rather than a single key which you later have to lookup. It also has performance O(n), which is ok.
Example:
array_usearch($arr, function ($o) { return $o->name != 'zero'; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With