Link to home
Start Free TrialLog in
Avatar of dolythgoe
dolythgoe

asked on

Deleting a value from an array

Hi all,

I have an array stored in a $_SESSION. I'm trying to remove an element but it doesn't seem to be working.

unset($_SESSION['favorite_link_array'][$link_id]);

Open in new window


The array is a list of ids in no particular order like array(12453, 23123, 23424, 43535, 64334) etc..

How do I delete an entry with a matching value? Like from the above example, remove 23424.

Cheers
SOLUTION
Avatar of babblo
babblo
Flag of Argentina image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Usage Example Line 5 above should be

$newArray = remove_item_by_value($myArray, $removeThis);

I guess... are you sure $_SESSION['favorite_link_array'] is array? Maybe it is just a string!
in that case, you can use replace function, or split it make array, remove one item and then join the array to make it a string again and put into session back as string...

$_SESSION['favorite_link_array'] = replace($_SESSION['favorite_link_array'], $link_id,"");

but php supports array in session, so using it as array will make life easier...

http://stackoverflow.com/questions/2306159/array-as-session-variable

your code looks fine as long as yo have a valid array in session...
<?php
$myArray = array('item1', 'item2', 'item3' ...);
$removeThis = 'item2';

$newArray = remove_item_by_value($myArray, $removeThis);
?>

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dolythgoe
dolythgoe

ASKER

Cheers guys - Ray, professional as always :)

Yes, they are indeed unique values.

So populating your later example, would that be something like:

		while($row=mysqli_fetch_array($result))
		{
			$favorite_link_array[$row['link_id']] = $row['link_id'];
		}

Open in new window

Yes, that looks right to me.