removing one element from an array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
SilvrWolf
Forum Newbie
Posts: 7
Joined: Sun Aug 11, 2002 11:00 am

removing one element from an array

Post 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?
User avatar
hob_goblin
Forum Regular
Posts: 978
Joined: Sun Apr 28, 2002 9:53 pm
Contact:

Post by hob_goblin »

try using

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

why don't you just use unset() though?
SilvrWolf
Forum Newbie
Posts: 7
Joined: Sun Aug 11, 2002 11:00 am

Post 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!!
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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 ;)
SilvrWolf
Forum Newbie
Posts: 7
Joined: Sun Aug 11, 2002 11:00 am

Ill try that

Post 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.
Post Reply