0

If I have an array in the following format, how can I assign part of these array values in to a new array? (Numeric value 123 and 654 indicate that the array can be separated in these locations)

$fruits = array();
$vehicles = array();
$all_words = array ("123", "apple", ”orange”, ………, ”bannana”, ”123”, ”654”, ”car”, ”bus”, ………, ”train”, ”bike”, ”654”); 
//continuous ……… Indicate there can be unknown amount of array elements.
//Also, these numeric values of 123 and 645 can be changed to something convenient 

I can see that using $fruits = array_slice($array, 1, 5) I can get a portion of this array in to a new one. But if I don’t know the length of array between two numbers(123 and 654, how can I assign these values in to an new array?

1
  • Thanks for all of your detailed answers and comments. it helped a lot. Commented Jul 3, 2013 at 6:00

2 Answers 2

2

You can get their index using array_search() and then use them for slicing, like this..

$index1 = array_search('123', $all_words); 
$index2 = array_search('654', $all_words); 
$vehicles = array_slice($array, $index1, $index2-$index1+1);
Sign up to request clarification or add additional context in comments.

1 Comment

no reason to upvote, you forgot to +1 each index, because array_search will return 0 in this example but you need 1 for array_slice
0

$fruits = array_slice($array, array_search('123', $array)+1, array_search('654', $array)+1)

Comments

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.