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.

3

6 Answers 6

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);
Sign up to request clarification or add additional context in comments.

1 Comment

You guys are quick today.
1
unset($my_array[1] , $my_array[0]);
$my_array = array_values($my_array);

Comments

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));

Comments

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>';

1 Comment

Thanks problem solved :) but in your code 4th line shoud be correct
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);

Comments

0

Use the array_values fonction:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.