我試圖做一個腳本來從我的數組中刪除任何空元素。刪除陣列中的[0]元素,而不刪除整個陣列
然而,一個空的元素在[0]插槽中,所以當我取消設置值時,它會刪除我的整個數組。至少我認爲這就是發生了什麼,爲什麼這不起作用?
<?php
$idfile = file_get_contents("datafile.dat");
$idArray = explode("\n", $idfile);
print_r($idArray);
foreach ($idArray as $key => &$value) {
echo "Key is: ".$key." and value is: ".$value."<br />\n";
if ($value == ""){
echo "Killing value of ".$value."<br />";
unset($value[$key]);
}
$value = str_replace("\n", "", $value);
$value = str_replace("\r", "", $value);
$value = $value.".dat";
}
print_r($idArray);
?>
下面是輸出:
Array
(
[0] =>
[1] => test1
[2] => test2
)
Key is: 0 and value is: <br>
Killing value of <br>
嘗試[ array_shift()](http://www.php.net/manual/en/function.array-shift.php)刪除第一個元素 – 2012-08-08 20:08:42
我會在其中添加一個額外的函數來檢查值是否爲「 0「然後使用這個。 – 2012-08-08 20:10:15
[刪除空數組元素]可能的重複(http://stackoverflow.com/questions/3654295/remove-empty-array-elements) – 2012-08-08 20:10:42