1

When trying to print/echo a specific part of my session array it wont return anything besides a '1'

it also gives an error telling me that user_name is an undefined index but when I var_dump my session it shows it exists.

What is the correct way to only show the user_name part of my session on screen?

I've tried print_r, echo, print but none of these seem to work

session_start();

include '../php/database.php';
var_dump($_SESSION['userdata']);
echo "Welcome back " . print_r($_SESSION['userdata']['user_name'][0]) . "!";

I expect the output to be "Welcome back user_name" which in this case should be the text string "empty"

var_dump:

array(1) { [0]=> array(1) { [0]=> array(8) { ["user_id"]=> string(1) "1" [0]=> string(1) "1" ["user_name"]=> string(5) "empty" [1]=> string(5) "empty" ["user_pass"]=> string(5) "empty" [2]=> string(5) "empty" ["user_email"]=> string(17) "empty@hotmail.com" [3]=> string(17) "empty@hotmail.com" } } }

output

Notice: Undefined index: user_name in C:\xampp\htdocs\Projecten\loginSystem\pages\dashboard.php on line 7 Welcome back 1!

M. Eriksson
  • 13,450
  • 4
  • 29
  • 40
daveyvdweide
  • 102
  • 1
  • 10
  • Have you checked whether your structure really matches? As far as I see, there is no element `user_name` within the given dump - the array has a single element, another array, at index `0` – Nico Haase Jan 25 '19 at 12:58
  • 3
    Possible duplicate of ["Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined) – Nico Haase Jan 25 '19 at 12:59

2 Answers2

2

There are 2 arrays in your session Do it this way:

echo "Welcome back " . print_r($_SESSION['userdata'][0][0]['user_name']) . "!";
MatejG
  • 1,393
  • 1
  • 17
  • 26
1

As you mentioned your session data is like:

array(1) {
    [0]=> array(1) { 
        [0]=> array(8) { 
            ["user_id"]=> string(1) "1" [0]=> string(1) "1" 
            ["user_name"]=> string(5) "empty" [1]=> string(5) "empty" 
            ["user_pass"]=> string(5) "empty" [2]=> string(5) "empty" 
            ["user_email"]=> string(17) "empty@hotmail.com" [3]=> string(17) "empty@hotmail.com" 
        } 
    } 
}

To get user_name, You will have to travel through your array as:

echo $_SESSION['userdata'][0][0]['user_name'];
Rohit Ghotkar
  • 803
  • 5
  • 17