On 20 March 2015 at 22:12, Stanislav Malyshev <smalys...@gmail.com> wrote:

> You're not using the keys in foreach, so why you need to preserve them?


This was merely an example of the features equal part in current code, not
a real life use case.

Using the new syntax will keep the keys preserved, therefore any example
showing how to do the same *must* do the same, which preserving keys does.

This may be not so easy to implement - imagine passing $array[*1:4] by
> reference.


This would be the same as doing
$array[array_keys($old_array)[1]] = $new_array[0];
$array[array_keys($old_array)[2]] = $new_array[1];
$array[array_keys($old_array)[3]] = $new_array[2];
$array[array_keys($old_array)[4]] = $new_array[3];

The new syntax helps clean that up, by doing:

$array[*1:4] = [1,2,3,4];

There is nothing to pass by reference that is different, the array is still
$array, it is just having the values replaced in bulk by index (not by key)

This sort of code would be needed:

<?php
$old_array = [0 => 1, 1 => 2, 5 => 3, 7 => 4, 4 => 5, 2 => 6, 14 => 7, 55
=> 8];

$new_array_values = ['foo', 'bar', 'baz'];

// To replace the third, fourth and fifth element.

$old_array[array_keys($old_array)[3]] = $new_array_values[0];
$old_array[array_keys($old_array)[4]] = $new_array_values[1];
$old_array[array_keys($old_array)[5]] = $new_array_values[2];

var_dump($old_array);

Instead of, what is in my opinion, much cleaner:

<?php
$old_array = [0 => 1, 1 => 2, 5 => 3, 7 => 4, 4 => 5, 2 => 6, 14 => 7, 55
=> 8];

$new_array_values = ['foo', 'bar', 'baz'];

$old_array[*3:5] = $new_array_values;

var_dump($old_array);


There is the array_splice method that can do the same thing, however this
to me is less obvious as to what is happening:

<?php
$old_array = [0 => 1, 1 => 2, 5 => 3, 7 => 4, 4 => 5, 2 => 6, 14 => 7, 55
=> 8];

$new_array_values = ['foo', 'bar', 'baz'];

// To replace the third, fourth and fifth element.

array_splice($old_array, 3, 3, $new_array_values);

var_dump($old_array);

Reply via email to