0

We have an array of ranges in $r:

$r = array( array(3,5), array(36,54) );

We want to add a new range to our ranges:

$n = array(11, 19);

We also want $r to be sorted, so the new range should be inserted at position 1. If we use array_splice the result would be having 11 and 19 added as two new elements:

array_splice($r, 1, 0, $n);
// output: array( array(3,5), 11, 19, array(36,54) )

How can we get the desired result as shown below?

// output: array( array(3,5), array(11,19), array(36,54) )
1
  • have you tried adding another dimension to $n? $n=array(array(11,19)) and splicing that? Commented Apr 22, 2015 at 8:37

3 Answers 3

3

You can wrap array with new range in another array:

array_splice($r, 1, 0, array($n));

Output:

array(3) {
  [0]=>
  array(2) {
    [0]=>
    int(3)
    [1]=>
    int(5)
  }
  [1]=>
  array(2) {
    [0]=>
    int(11)
    [1]=>
    int(19)
  }
  [2]=>
  array(2) {
    [0]=>
    int(36)
    [1]=>
    int(54)
}

Example

Sign up to request clarification or add additional context in comments.

Comments

2

This may be easier that you think. Reading array_splice's documentation, you see that the $replacement parameter is an array and should contain all elements that should be inserted into the array.

So consider the following code:

array_splice($r, 1, 0, array(11, 19));

This does not insert array(11, 19) as one element into the array, but each 11 and 19 as two elements.

What you probably want to do is this:

array_splice($r, 1, 0, array(array(11, 19)));

Or, in your concrete example:

array_splice($r, 1, 0, array($n));

Alternatively, you could simply append and then completely re-sort the array (which might be not as efficient, but a bit easier for small data sets):

$r[] = $n;
usort($r, function($a, $b) { return $a[0] - $b[0]; });

Comments

0

If you are simply wanting them to be in order of the first value in the range, then you could do the following.

$r = array( array(3,5), array(36,54));
$r[] = array(11,19);
print_r($r);
sort($r);
print_r($r);

results:

Not sorted:

Array
(
    [0] => Array
        (
            [0] => 3
            [1] => 5
        )

    [1] => Array
        (
            [0] => 36
            [1] => 54
        )

    [2] => Array
        (
            [0] => 11
            [1] => 19
        )

)

Sorted:

Array
(
    [0] => Array
        (
            [0] => 3
            [1] => 5
        )

    [1] => Array
        (
            [0] => 11
            [1] => 19
        )

    [2] => Array
        (
            [0] => 36
            [1] => 54
        )

)

view this answer to another question that explains why sort() works on multidimensional arrays

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.