0

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_array(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

1
  • 2
    If you plan to put this in a custom function I find it a bad idea to use global. Commented Jan 8, 2011 at 1:38

4 Answers 4

2

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.
Sign up to request clarification or add additional context in comments.

Comments

1
$new=array_slice($old_array,0,3);

Comments

0

Use array_slice().

Comments

0

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.

1 Comment

It would be nice if you could actually show how to use it to answer this specific question instead of just lifting examples from the manual.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.