Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract certain values from an array

Tags:

php

slice

Example from here http://php.net/manual/en/function.array-slice.php

$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 2);      // returns "c", "d", and "e"
$output = array_slice($input, -2, 1);  // returns "d"
$output = array_slice($input, 0, 3);   // returns "a", "b", and "c"

But how to get for example "a", "d", and "e"?

like

$output = array_slice($input, 0, 1);
$output = array_slice($input, 3, 1);
$output = array_slice($input, -1, 1);

But in one variable. Is it possible?

Update. Want to use 1st, 3rd and last element of array. As if extract 1st, 3rd and last element and create new array only with the 3 elements.

like image 819
user2232696 Avatar asked May 06 '13 08:05

user2232696


1 Answers

You will have to throw array_merge() into the mix, because array_slice() can only extract a subsequence of an array, not an arbitrary number of elements spread over the entire array. Extract each subsequence separately and then merge them into one array:

$slice1 = array_slice($input, 0, 1);
$slice2 = array_slice($input, -2, 2);
$output = array_merge($slice1, $slice2);

Be aware however, that this will only work, if you really know each element in your array. In this case, you could just as well use direct array access, which will most likely generate less overhead and is much easier to read:

$output = array($input[0], $input[3], $input[4]);

It might be much more reasonable to use array_filter() or even a custom iterator. But you haven't provided enough information about your task to clearly say something about that.

Edit:
If it's only a matter of notation, you could try specifying an array with all the relevant indexes, then switch it around using array_fill_keys() in order to use it with array_intersect_key() to extract only the relevant elements from the array:

$indexes = array(0, 3, 4);
$indexArray = array_fill_keys($indexes, true);
$output = array_intersect_key($input, $indexArray);
like image 105
Till Helge Avatar answered Nov 08 '22 14:11

Till Helge