Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP : Insert an array into another array

I'm trying to normalize a string of comma-separated numbers, and a range as well. To demonstrate:

the array :

$array = ["1","2","5-10","15-20"];

should become :

$array = [1,2,5,6,7,8,9,10,15,16,17,18,19,20];

The algorithm i'm working on is :

//get the array values with a range in it :
$rangeArray = preg_grep('[-]',$array);

This will contain ["5-10", "16-20"]; Then :

foreach($rangeArray as $index=>$value){
    $rangeVal = explode('-',$value);
    $convertedArray = range($rangeVal[0],$rangeVal[1]);
}

The converted array will now contain ["5","6","7","8","9","10"];

The problem I now face is that, how do I pop out the value "5-10" in the original array, and insert the values in the $convertedArray, so that I will have the value:

$array = ["1","2","5","6","7","8","9","10","16-20"];

So, how do I insert an array into an array? Or is there a cleaner way to solve this kind of problem? converting array of both numbers and range values to array of properly sequenced numbers?

like image 855
muffin Avatar asked Jul 02 '15 09:07

muffin


People also ask

How can I add one array to another array in PHP?

Given two array arr1 and arr2 and the task is to append one array to another array. Using array_merge function: This function returns a new array after merging the two arrays. $arr1 = array ( "Geeks" , "g4g" );

How do I add one array to another?

To append one array to another, call the concat() method on the first array, passing it the second array as a parameter, e.g. const arr3 = arr1. concat(arr2) . The concat method will merge the two arrays and will return a new array.

How do I copy one array to another in PHP?

The getArrayCopy() function of the ArrayObject class in PHP is used to create a copy of this ArrayObject. This function returns the copy of the array present in this ArrayObject.

What is array_push in PHP?

Definition and Usage. The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).


1 Answers

you did not finish a little

$array = ["1","2","5-10","15-20"];
// need to reverse order else index will be incorrect after inserting
$rangeArray = array_reverse( preg_grep('[-]',$array), true);

$convertedArray = $array;

foreach($rangeArray as $index=>$value) {

    $rangeVal = explode('-',$value);
    array_splice($convertedArray, $index, 1, range($rangeVal[0],$rangeVal[1]));
}

print_r($convertedArray);
like image 105
splash58 Avatar answered Oct 05 '22 22:10

splash58