Banjerr
Banjerr

Reputation: 121

Assign element from array to variable?

I am trying to pull an element out of an array to assign it to a variable, but not having much luck so far... This is my code.

$email = $clientEmail;
$returnFields = array('Id', 'FirstName');
$data = $app->findByEmail($email, $returnFields);
if($debug){
    echo "<pre>Contact Info:";
    print_r($data[0]);
    echo "ID is:";
    list($contactId, $contactName) = $data[0];
    echo $contactId;
    echo "</pre>";
}

Which returns this...

Contact Info:Array
(
[FirstName] => Scooby1
[Id] => 59871
)
ID is:

I've tried using the list(), explode(), and implode(), but I can't seem to pull [Id] out and assign it's value to a variable. How else can I go about this?

Upvotes: 0

Views: 56

Answers (1)

Tom
Tom

Reputation: 642

In php manual you can find following, "list() only works on numerical arrays and assumes the numerical indices start at 0.", So your code can't work properly.

You can change it to

$contactName = $data[0]['FirstName'];
$id = $data[0]['Id'];

Or you can change findByEmail method to return numerical array

$result->fetch(PDO::FETCH_NUM))

Or even this kind of magic should work

$numericalArray = (array) $data[0];
list($contactName, $id) = $numericalArray;

Upvotes: 1

Related Questions