Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array function that returns a subset for given keys

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.

like image 379
user1517081 Avatar asked Sep 22 '12 11:09

user1517081


People also ask

What is array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.

What is the use of Array_flip () function?

The array_flip() function flips/exchanges all keys with their associated values in an array.

What does Array_splice () function do give an example?

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

What does In_array return in PHP?

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.


2 Answers

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); 
like image 148
Maciej Lew Avatar answered Oct 06 '22 01:10

Maciej Lew


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) {
}
like image 31
Pradeep Sanjaya Avatar answered Oct 06 '22 00:10

Pradeep Sanjaya