Page 1 of 1

removing one element from an array

Posted: Sun Aug 18, 2002 7:04 pm
by SilvrWolf
I am trying to remove an element from an array by using array_splice. If this is wrong then please tell me.
I have re-read the php manual several times but still this doesn't work

Code: Select all

$key_id = array_search($student_id, $student_list);
if (!$key_id) {
	echo "There was an error. Student not found in student list.";
	}
	echo "key_id is: ".$key_id;
$student_list = array_splice($student_list, (1+$key_id), 1);
I have tried one other variation where I just use $key_id instead of (1+$key_id)
any ideas?

Posted: Sun Aug 18, 2002 7:26 pm
by hob_goblin
try using

$student_list = array_splice($student_list, $key_id++, 1);

why don't you just use unset() though?

Posted: Sun Aug 18, 2002 7:33 pm
by SilvrWolf
unset will punch a hole in the array and then when I iterate through again (if someone needs to be deleted) Ill get an undefined offset.

update: the above code didn't work.

arrays are the craziest people!!

Posted: Sun Aug 18, 2002 8:42 pm
by volka

Code: Select all

$key_id = array_search($student_id, $student_list); 
if (!$key_id)
   echo "There was an error. Student not found in student list."; 
else
{
   echo "key_id is: ".$key_id;
   array_splice($student_list, $key_id, 1);
}
//print('<pre>'); print_r($student_list); print('</pre>');
array_splice alters the array given as parameter and returns the elements it removed.

p.s.: using unset array_search and foreach will be still able to iterate the array ;)

Ill try that

Posted: Mon Aug 19, 2002 12:06 pm
by SilvrWolf
volka, Ill give that a shot. For now I just set the value to NULL for the corresponding key and then used logic to omit any NULL values from the list.