Resize array

0

I have the following question, for example

<?php
$cesta = array("laranja", "banana", "melancia", "morango");
$fruta = array_pop($cesta);
print_r($cesta);
?>

the initial array goes from 0 to 3, when I do array_pop it stays from 0 to 2, but if I add a new element the positions of the array will be, (0,1,2,4). Is there a way to put the positions as (0,1,2,3) excluding one element and adding another then?

    
asked by anonymous 05.06.2017 / 23:44

1 answer

0

If the index sequence break is the problem as in the code below:

<?php

   $cesta = array("laranja", "banana", "melancia", "morango");
   unset($cesta[1]);
   $cesta[] = "novo";

You can create a new variable and reset the indexes using the array_merge() function it will create a new array with the array passed as an argument. You can get the same result with array_values()

Example - ideone

<?php

   $cesta = array("laranja", "banana", "melancia", "morango");
   unset($cesta[1]);
   print_r($cesta);
   $cesta[] = "novo";
   print_r($cesta);

   $novo = array_merge($cesta);

   print_r($novo);
    
06.06.2017 / 00:06