Question:
Introductory: there is an array with keys, there is a string with several keys, one of which will fit this array (i.e., an element with such a key will exist).
The task is at least: it is most beautiful to get the value of the first element of the array, the key of which is suitable.
The maximum task is to get the value of the first element of the array in the most beautiful way, the key of which is suitable, and if several keys are suitable, give an error.
The task is beyond the maximum: it is most beautiful to get the value of the first element of the array, the key of which is suitable, and if several keys are suitable, give an error. In this case, if the key is passed as fields[name_1]
, you need to understand what is meant by nesting in an element and process the next element of the array in accordance with this.
At the moment, the minimum task has been implemented, but without beauty, in my opinion. Here is the code:
function get_non_zero( $str_keys, $data ) {
$keys = explode( ',', $str_keys );
foreach ( $keys as $key ) {
if ( ! empty( $data[ $key ] ) ) {
return $data[ $key ];
}
}
return null;
}
$data = ['key0' => 0, 'key1' => 1, 'key3'=> 3];
echo( get_non_zero( 'key1,key2', $data ) ); // выведет 1
Maybe someone has ideas how to implement this more clearly and beautifully, perhaps without a function at all?
Answer:
If you write for yourself, then you can do this:
$data = ["key0" => 0, "key1" => 1, "key3"=> 3];
$search = array_flip(explode(",", "key1,key2"));
$result = array_intersect_key($data, $search);
echo count($result) > 1 ? null : array_pop($result);
If others will work with the code, then it is better in a function, with comments and beautiful branching.
function getNonZero($keys, $data)
{
$search = array_flip(explode(",", $keys));
$result = array_intersect_key($data, $search);
if (count($result) > 1):
return null;
else:
return array_pop($result);
endif;
}
$data = ["key0" => 0, "key1" => 1, "key3"=> 3];
$search = "key1,key2";
echo getNonZero($search, $data);
"Over maximum" :
function searchInArray($value)
{
preg_match("([\w+]{1,})", $value, $matches);
return !empty($matches) ? $matches[0] : $value;
}
function getNonZero($search, $data)
{
$search = array_map("searchInArray", explode(",", $search));
$result = array_intersect_key($data, array_flip($search));
if (count($result) === 1):
return is_array($result) ? array_shift($result[key($result)]) : $result;
else:
return null;
endif;
}
$data = ['key0' => 0, 'fields' => ['name_1'=>1], 'key3'=> 3];
$sting = 'name,entry.436917433,billing_first_name,fields[name_1]';
echo getNonZero($sting, $data);