Click here to Skip to main content
15,896,915 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have an array I'm storing in a session variable. When this page is loaded, an id is given. I need to loop through the array and find that variable, then delete that element from the array. I've tried using unset, and I don't know if there's an error in my logic somewhere, but I can't seem to get this to work. I've been at it all day, and have the page echoing out pretty much everything. Anyone who could help would be appreciated.
PHP
<?php
	session_start();
	
	$id = $_GET["id"];
	$name = $_GET["name"];
	$action = $_GET["action"];
	
	if (empty($_SESSION["people"])) {
		$_SESSION["people"] = array();
	}
	
	$people = $_SESSION["people"];
	
		$i = 0;
		echo "<p>Test: " . $people[0][0] . "</p>";
		echo "<p>Before Array: ";
		var_dump($_SESSION["people"]);
		echo "</p>";
		
		foreach ($people as $item) {
			echo "<p>Searching for: " . $id . "</p>";
			echo "<p>Current ID: " . $item[0] . "</p>";
			if ($item[0] == $id) {
				echo "Removing: " . $i;
				unset($people[$i]);
			} else {
				$i++;
			}
		}
		
		echo "<p>After Array: ";
		var_dump($_SESSION["people"]);
		echo "</p>";

		$_SESSION["people"] = $people;
	}

	foreach($people as $item) {
		echo "
			<input style=\"border: 1px solid #b97819; padding: 0 2px 0 2px; border-radius: 6px;\" type=\"button\" value=\"" . $item[1] . "\" onClick=\"removeContact(" . $item[0] . ");\" />
		";
?>
Posted
Comments
Matej Hlatky 19-Jun-13 2:51am    
First, you are dumping $_SESSION["people"] in the "Before Array" and "After Array" blocks, but you are working with $people variable.
Try to unset right from $_SESSION["people"], not from the $people variable.
Update the question with observed behavior.
You should break the foreach cycle after you found the right item.
You can also use alternative usage of PHP foreach: foreach ($people as $i => $item), so you don't need to handle that variable manually.
Jack R. Schaible 19-Jun-13 20:37pm    
I tried removing right from session using unset($_SESSION["people"][$i]); and it didn't work.

1 solution

Apparently, reassigning the array variable to the return of array_values($people) did the trick. Not sure why or how.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900