0

I have several values stored in $_SESSION beginning with 'first_name_' & 'last_name_' which then a number appended to the end deepening on how many names are generated.

I am able to extract each of these values from the session and add to an array but would like to pair up the first and last names together within a nested array. (if that makes sense)

at the moment I have:

$users_array = array();

foreach ($_SESSION as $key => $value) {
    if(strpos($key, 'first_name_') === 0) {
        $users_array[] = $value;            
}
    if(strpos($key, 'last_name_') === 0) {
        $users_array[] = $value;
    }
}

This produces an output with var_dump:

array
0 => string 'John' (length=4)
1 => string 'Smith' (length=8)
2 => string 'Jane' (length=4)
3 => string 'Doe' (length=3)

But what I would like is something like:

array
'user' => 
    array
    'first_name' => string 'John' (length=4)
    'last_name' => string 'Smith' (length=5)
    array
    'first_name' => string 'Jane' (length=4)
    'last_name' => string 'Doe' (length=5)

Any suggestions on how I can achieve this?

3
  • Why aren't they stored in that format in the session to begin with? Commented Nov 28, 2013 at 19:41
  • Not sure, this just seemed the easiest way to do what I wanted. It may be better to store them like that in the session, could you provide an example? Commented Nov 28, 2013 at 19:59
  • Uhm... $_SESSION['users'][] = array('first_name' => 'John', 'last_name' => 'Doe') when putting them into the session...?! Commented Nov 28, 2013 at 20:03

1 Answer 1

1

deceze is right in his comment... But just so people with similar issues with creating 2-dimensional array from a 1-dimensional array, here is a solution. Also, note that PHP does not guarantee that the order will be same when iterating using FOREACH. As this will work, it is still prone to errors.

$users_array = array();

foreach ($_SESSION as $key => $value) {
    if(strpos($key, 'first_name_') === 0) {
        $users_array[] = array();
        $users_array[count($users_array)-1]['first_name'] = $value;         
}
    if(strpos($key, 'last_name_') === 0) {
        $users_array[count($users_array)-1]['last_name'] = $value;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.