简体   繁体   中英

Remove element from array, not using unset()

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

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

您是否要通过重新索引删除特定的单个数组项目?

array_splice($a, $index_to_remove, 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/>";
}

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";
}

?>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM