2016-04-28 96 views
0

請幫助 時,我想喲當我打印陣列之後從陣列布歐中刪除一個元素它顯示錯誤注意未定義偏移:3行號16如何刪除陣列的PHP的值

<?php 
    $value = 22; 
    $numbers = array(4, 6, 2, 22, 11); 
    $arrlength = count($numbers); 

    for($y = 0; $y < $arrlength ; $y++) { 
     if ($numbers[$y] == $value) { 
      unset($numbers[$y]); 
     } 
    } 
    $arrlength = count($numbers); 
    for($x = 0; $x < $arrlength; $x++) { 
     echo $numbers[$x]; 
     echo "<br>"; 
    } 
?> 
+1

在php中的數組不會重新索引,所以'$ numbers [3]'將會被取消定義。使用'foreach'來遍歷數組或使用'array_values()'手動重新索引。 – jeroen

回答

0

使用array_values()

<?php 
$value = 22; 
$numbers = array(4, 6, 2, 22, 11); 
$arrlength = count($numbers); 

for($y = 0; $y < $arrlength ; $y++) { 
if ($numbers[$y] == $value) { 
    unset($numbers[$y]); 
} 
} 
$numbers = array_values($numbers); 
$arrlength = count($numbers); 
for($x = 0; $x < $arrlength; $x++) { 
echo $numbers[$x]; 
echo "<br>"; 
} 
?> 

檢查在線演示:Click Here

OR

<?php 
$value = 22; 
$numbers = array(4, 6, 2, 22, 11); 
$arrlength = count($numbers); 

for($y = 0; $y < $arrlength ; $y++) { 
if ($numbers[$y] == $value) { 
    unset($numbers[$y]); 
} 
} 
//$numbers = array_values($numbers); 
//$arrlength = count($numbers); 
foreach($numbers as $key=>$num) { 
echo $num; 
echo "<br>"; 
} 
?> 
0

你要打印不存在關鍵

的元素試試這個:

<?php 
$value = 22; 
$numbers = array(4, 6, 2, 22, 11); 
$arrlength = count($numbers); 

for($y = 0; $y < $arrlength ; $y++) { 
    if ($numbers[$y] == $value) { 
     unset($numbers[$y]); 
    } 
} 
foreach($numbers as $k => $number) 
    echo "key: ". $k . " value: ". $number . "<br />";