0

If I use unset() I get error: Undefined offset: on index I deleted. How could I remove this appropriately ?

PHP:

<pre>
<?php

$a = array("foo", "baa", "ahahaha");

unset($a[1]);
//echo '<pre>'; print_r($a);

for($i = 0; $i < count($a); $i++) {
    echo 'val at ', $i;
    echo " ", $a[$i], "\r\n";
}

?>

error:

Notice: Undefined offset: 1 in file.php

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
The Mask
  • 17,007
  • 37
  • 111
  • 185

5 Answers5

3

You need to reindex the array to loop over it with an incrementing number:

unset($a[1]);
$a = array_values($a);

for($i = 0; $i < count($a); $i++) {
    echo 'val at ', $i;
    echo " ", $a[$i], "\r\n";
}

Or just foreach the array:

foreach($a as $key => $val) {
    echo 'val at ', key;
    echo " ", $val, "\r\n";
}

For completeness, you can also merge with an empty array to reindex:

unset($a[1]);
$a = array_merge(array(), $a);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
3

Are you wanting to remove a specific single array item, with re-indexing?

array_splice($a, $index_to_remove, 1);
ludwigmace
  • 692
  • 4
  • 10
1

If you want to avoid undefined errors. You can use foreach

unset($a[1]);
foreach($a as $key => $value) {
    echo 'val as' . $key;
    echo ' ' . $value . "<br/>";
}
user1978142
  • 7,946
  • 3
  • 17
  • 20
1

Reindex the array is the solution, remember you're removing one element and with the for iteration loops trough all items including index 1

<pre>
<?php

$a = array("foo", "baa", "ahahaha");

unset($a[1]);

$newarray = array_values($a); // here reindex the array
//echo '<pre>'; 
print_r($newarray);

for($i = 0; $i < count($newarray); $i++) {
    echo 'val at ', $i;
    echo " ", $newarray[$i], "\r\n";
}

?>
martinezjc
  • 3,415
  • 3
  • 21
  • 29
1

I think your question has directed the unset error at the wrong place to be honest. Unset DID work. It was the "for" loop that created the error.

The problem you had was that, when you unset the key you removed the key name "1". It didn't then update the array index, and as a result, the array then contained only the keys "0" and "2". "1" did not exist.

Your "for" loop then tried to look at $a[1] and it wasn't there. Yes, there are two elements left but they aren't called "0" and "1" but "0" and "2".

Solution: To remove an element from an array, but then update the index you need to do this......

$r = 1; // The index number you want to remove.
array_splice($a,$r,1);

// Get value you removed?
$ir = array_slice($a,$r,1);
echo "Just removed $ir[0] from array";
Adam
  • 359
  • 3
  • 5