I'm looking for an array function that does something like this:
$myArray = array(
'apple'=>'red',
'banana'=>'yellow',
'lettuce'=>'green',
'strawberry'=>'red',
'tomato'=>'red'
);
$keys = array(
'lettuce',
'tomato'
);
$ret = sub_array($myArray, $keys);
where $ret is:
array(
'lettuce'=>'green',
'tomato'=>'red'
);
A have no problem in writing it down by myself, the thing is I would like to avoid foreach loop and adopt a built-in function or a combination of built-in functions. It seems to me like a general and common array operation - I'd be surprised if a loop is the only option.
The array_keys() function returns an array containing the keys.
The array_flip() function flips/exchanges all keys with their associated values in an array.
The array_splice() function removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements. Tip: If the function does not remove any elements (length=0), the replaced array will be inserted from the position of the start parameter (See Example 2).
The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.
This works:
function sub_array(array $haystack, array $needle) { return array_intersect_key($haystack, array_flip($needle)); } $myArray = array( 'apple'=>'red', 'banana'=>'yellow', 'lettuce'=>'green', 'strawberry'=>'red', 'tomato'=>'red' ); $keys = array( 'lettuce', 'tomato' ); $ret = sub_array($myArray, $keys); var_dump($ret);
You can use array_intersect_key, but it uses second array with keys and values. It computes the intersection of arrays using keys for comparison
array_intersect_key
<?php
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8);
$array3 = array('green' => '', 'blue' => '', 'yellow' => '', 'cyan' => '');
$array4 = array('green', 'blue', 'yellow', 'cyan');
var_dump(array_intersect_key($array1, $array2));
var_dump(array_intersect_key($array1, $array3));
var_dump(array_intersect_key($array1, $array4));
?>
The above example will output:
array(2) {
["blue"]=>
int(1)
["green"]=>
int(3)
}
array(2) {
["blue"]=>
int(1)
["green"]=>
int(3)
}
array(0) {
}
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