tsiro
tsiro

Reputation: 2383

how can i access the elements of array which is located in a value of associative array in php

I have an array which holds the data returned from an sql query

$user = $stmt->fetch(PDO::FETCH_ASSOC);
$user["username"] = "username1";
$user["password"] = "password1";

I have also an associative array where $user array is saved as a value of a key:

return array("invalid credentials:"=>"false", "credentials"=>$user);

My question is how can I access the values($user) of "credentials" key I have tried $user["credentials"] => "username"; but this obviously does not work

Upvotes: 0

Views: 34

Answers (2)

Nishanth Matha
Nishanth Matha

Reputation: 6081

Here's an idea of how to achieve it

$functionReturn = array("invalid credentials:"=>"false", "credentials"=>$user);

$user = $functionReturn['credentials'];
var_dump($user["username"],$user["password"]);

or alternatively just:

$functionReturn['credentials']["username"];
$functionReturn['credentials']["password"];

Upvotes: 1

worldofjr
worldofjr

Reputation: 3886

You can access the value of a multidimentional array by stacking the keys in brackets;

So if your function returned the array you've created to $arr

$arr = somefunction(); // whatever the function you're calling is named
$username = $arr['credentials']['username'];

Hope this helps.

Upvotes: 1

Related Questions