0

I come across a scenario where i have an array like this

 Array
    (
        [24] => 24
        [25] => 25
        [26] => 26
        [27] => 27
        [28] => 28
        [29] => 29
    )

But i want a resultant array by including the incremented value of last and decremented value of first like this

Array
(
    [24] => 24
    [25] => 25
    [26] => 26
    [27] => 27
    [28] => 28
    [29] => 29
    [23] => 23
    [30] => 30
)

I know this is a little bit strange. But can anyone help me to find the result.

I found out the values

$f=reset($res);
$f=$f-1;

$l=end($res);
$l=$l+1;

but no idea on how to push into array

Imran
  • 21
  • 5

2 Answers2

0

It's probably safer to use min and max to find the lowest and highest values, otherwise your code wouldn't work on your result array (reset($array) on the output still returns 24, not 23):

$min = min($array) - 1;
$max = max($array) + 1;
$array[$min] = $min;
$array[$max] = $max;
print_r($array);

Output:

Array

(
    [24] => 24
    [25] => 25
    [26] => 26
    [27] => 27
    [28] => 28
    [29] => 29
    [23] => 23
    [30] => 30
)

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95
0

Under the condition that the key is always equal to the value you can try that:

$data = [
  24 => 24,25 => 25,26 => 26,27 => 27,28 => 28,29 => 29,
];

$first = reset($data)-1;
$end = end($data)+1;
$data[$first] = $first;
$data[$end] = $end;

But I think you do not want the first and last, but min and max.

jspit
  • 7,276
  • 1
  • 9
  • 17