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?
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);
$fruits = array_slice($array, array_search('123', $array)+1, array_search('654', $array)+1)