1. 程式人生 > >PHP刪除陣列指定元素

PHP刪除陣列指定元素

用unset刪除陣列中的某一下時,陣列的下標不會從新排序

例如

		$a=array("red", "green", "blue", "yellow");   
		count($a); 		//得到4   
		unset($a[1]); 	//刪除第二個元素   
		count($a); 		//得到3   
		echo $a[2]; 	//陣列中僅有三個元素,本想得到最後一個元素,但卻得到blue,   
		echo $a[1]; 	//無值

解決方法:

1.這是在獲取$a中元素時,需要判斷是否為null

2.使用array_splice (array input, int offset [, int length [, array replacement]])   PHP4中的方法進行元素刪除操作

$a=array("red", "green", "blue", "yellow");   
		count ($a); //得到4   
		array_splice($a,1,1); //刪除第二個元素   
		count ($a); //得到3   
		echo $a[2]; //得到yellow   
		echo $a[1]; //得到blue