Converting String to a $_SESSION result

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
jiminald
Forum Newbie
Posts: 2
Joined: Thu Oct 18, 2007 4:18 pm
Location: Cornwall, UK

Converting String to a $_SESSION result

Post by jiminald »

Hi,

My first time on these forums, so if I have posted it in the wrong place, sorry.

I am trying to convert {SESSION.value1.value2} to $_SESSION[value1][value2]
but the amount of values in the array can change.

Hope I explained that well.. and thanks in advanced! :)
User avatar
gregwhitworth
Forum Commoner
Posts: 53
Joined: Tue Oct 09, 2007 1:00 am
Location: Wasilla, Alaska

Post by gregwhitworth »

Nope - not well enough for me, but I'm a newb myself. You may want to post your actual PHP for the guru's to scrutinize.

--
Greg
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

I've actually done something extremely similar, so here's a little edited version I can share with you to demonstrate. Hope it helps.

Code: Select all

error_reporting(E_ALL);
session_start();

$_SESSION['foo']['bar']['foobar'] = 'w00t';

preg_match('#{SESSION\.([a-z0-9\.]+)}#i', '{SESSION.foo.bar.foobar}', $matches);

if (count($matches[1])) { 
	$keys = explode('.', $matches[1]);	
	
	// if only one key lets convert it to an array anyways
	if (count($keys) == 0) {
		$keys = array($matches[1][0]);
	}

	// holds the last key that is recursively searched 
	$lastkey = '';
	foreach ($keys as $key) {
		// determine if the key actually exists in the session 
		if (empty($lastkey) && isset($_SESSION[$key])) {
			$lastkey = $_SESSION[$key];
		}
		// determine if the last instance is an array and if we need to continue
		elseif (!empty($lastkey) && is_array($lastkey) && isset($lastkey[$key])) {
			$lastkey = $lastkey[$key];
		}
		// the value does not exist in the session
		else {
                        //reset the value to blank
                        $lastkey = '';
			break;
		}
	}	
	
	echo $lastkey;
}
jiminald
Forum Newbie
Posts: 2
Joined: Thu Oct 18, 2007 4:18 pm
Location: Cornwall, UK

Post by jiminald »

That worked brilliantly!
Had to mod slightly to fit but that saves me from another headache with it tonight!

Thanks :)
Post Reply