0

I tried to remove few array elements from my PHP script using PHP's unset() built-in funciton.
here is the code, that I tried.

<?php

$my_array = array('.','..','one','two','three','four');

unset($my_array[1] , $my_array[0]);

echo '<pre>';

print_r($my_array);

echo '</pre>';

?>

Then I got this output.

Array
(
    [2] => one
    [3] => two
    [4] => three
    [5] => four
)

but this is not what I'm expected. I want somthing like this.

Array
(
    [0] => one
    [1] => two
    [2] => three
    [3] => four
)

how can I achive this? thanks.

  • So you want to remove "." and ".." that you got from `scan_dir` ? That's a different question. – Clément Malet Sep 16 '14 at 12:40
  • 1
    possible duplicate of [How to Remove Array Element and Then Re-Index Array?](http://stackoverflow.com/questions/5217721/how-to-remove-array-element-and-then-re-index-array) – hlscalon Sep 16 '14 at 12:42
  • Either that or just [`array_shift()` twice](http://codepad.org/hK3AZ0ef) – kero Sep 16 '14 at 12:44

6 Answers6

4

yes that is the correct behavior, if you want to reset the keys you can use array_values()

$my_array = array('.','..','one','two','three','four');
unset($my_array[1] , $my_array[0]);
$my_array = array_values($my_array);
Kevin
  • 41,694
  • 12
  • 53
  • 70
1
unset($my_array[1] , $my_array[0]);
$my_array = array_values($my_array);
Sadikhasan
  • 18,365
  • 21
  • 80
  • 122
1

Use array_shift() function to remove the first element (red) from an array, and return the value of the removed element. We can get output as has u excepted.

$a=array('.','..','one','two','three','four');
array_shift($a); //array('..','one','two','three','four');
array_shift($a); // array('one','two','three','four');

Use array_pop() function to deletes the last element of an array. We can get output as has u excepted.

$a=array('.','..','one','two','three','four');
array_pop()($a); // array('.','..','one','two','three');
array_pop()($a); // array('.','..','one','two');

Use this function, array is indexed from zero every time. Otherwise use

$a= array('.','..','one','two','three','four');
unset($a[1] , $a[0]);
print_r(array_values(a));
Vamsi Krishna
  • 161
  • 10
0
$my_array = array('.','..','one','two','three','four');

unset($my_array[1] , $my_array[0]);

echo '<pre>';

print_r(array_values($my_array));

echo '</pre>';
Steve
  • 20,703
  • 5
  • 41
  • 67
0

Actually, you can find answer to your question in another:
rearrange array keys php

Just like it has been told, array_values would do the trick for you.

$arr = array_values($arr);
Community
  • 1
  • 1
kubilay
  • 5,047
  • 7
  • 48
  • 66
0

Use the array_values fonction:

From http://php.net/manual/en/function.array-values.php

Magador
  • 544
  • 5
  • 13