I'm trying to create an array based of another arrays values by defining a key?
E.g.
$old_array = array('hey', 'you', 'testing', 'this');
function get_new_array($key) {
global $old_array;
//return new array...
}
$new_array = get_new_arr开发者_开发知识库ay(2); //would return array('hey, 'you', 'testing'); as its the values of all the keys before the key 2 and the 2 key itself
Appreciate all help! :B
Use array_slice()
:
function get_new_array($key) {
global $old_array;
return array_slice($old_array, 0, $key+1);
}
Some suggestions:
- You wanted to return the sub-array up to and including the key. It's far more common to instead return up to but excluding the key. Hence the
+1
was necassary. - Using
$old_array
as a global is poor style. I recommend rather passing it as an argument to the function. - Since
array_slice()
already does what you want, except for minor differences, I'd call it directly rather than writing a wrapper function which hides functionality.
$new=array_slice($old_array,0,3);
Use array_slice().
Use array_slice() function:
$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"
Link to manual.
精彩评论