example 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", , "e" $output = array_slice($input, -2, 1); // returns "d" $output = array_slice($input, 0, 3); // returns "a", "b", , "c" but how example "a", "d", , "e"?
like
$output = array_slice($input, 0, 1); $output = array_slice($input, 3, 1); $output = array_slice($input, -1, 1); but in 1 variable. possible?
update. want use 1st, 3rd , last element of array. if extract 1st, 3rd , last element , create new array 3 elements.
you have throw array_merge() mix, because array_slice() can extract subsequence of array, not arbitrary number of elements spread on entire array. extract each subsequence separately , merge them 1 array:
$slice1 = array_slice($input, 0, 1); $slice2 = array_slice($input, -2, 2); $output = array_merge($slice1, $slice2); be aware however, work, if know each element in array. in case, use direct array access, generate less overhead , easier read:
$output = array($input[0], $input[3], $input[4]); it might more reasonable use array_filter() or custom iterator. haven't provided enough information task that.
edit:
if it's matter of notation, try specifying array relevant indexes, switch around using array_fill_keys() in order use array_intersect_key() extract relevant elements array:
$indexes = array(0, 3, 4); $indexarray = array_fill_keys($indexes, true); $output = array_intersect_key($input, $indexarray);
Comments
Post a Comment