Resize array

Asked

Viewed 93 times

0

I have the following question, for example

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

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

  • 1

    How did you insert the new element? I tested with $cesta[] = "maçã" and array_push($cesta, "maçã") and in both cases "apple" was inserted in index 3.

  • Seriously? to inserting directly with $basket[]="apple"

  • 1

    And how did you conclude that you were inserted in Index 4?

  • To reinforce the @Andersoncarloswoss comment see the test: http://ideone.com/PgiTwi

  • This is just an example you have on php.net, in my case I conclude because when I print_r(array), from Indice 7 it jumps to 12.

  • Can you put that code in the question?

  • The problem is when vc removes a middle element from the array and breaks the Indice sequence?

  • I think I identified the problem, I put a global variable to indicate the position of the array but it was not setting its value

Show 3 more comments

1 answer

0

If the breakdown of the index sequence 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 function array_merge() it will create a new array with the array passed as 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);
  • I was just about to quote array_values, I think she’s a lot faster than array_merge for this purpose.

  • @Andersoncarloswoss I think it’s the other way around: http://ideone.com/PlLH54 at least in this test.

  • I did tests using the microtime and even gave 10x faster, but I believe it is not very reliable the result.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.