user3764895 user3764895 - 5 months ago 19
PHP Question

PHP: Key Changes from Array to String

I am fairly new to PHP and am using it with the Facebook PHP SDK. Below, I am trying to get the 'name' fields of 'admin_creator' from the Facebook Graph API however the key changes from arrays to strings.

foreach($getAdminCreator as $key){
//var_export($key);
if(isset($key['admin_creator'])){
//var_export($key);
//var_export($key['admin_creator']);
foreach ($key['admin_creator'] as $key){
//var_export($key);
//echo $key['name'] . '<br>';
}
}
}


The entire thing works and
var_export(key)
would return an array up until the last foreach loop. Before entering the last foreach loop,
var_export($key['admin_creator']);
would return an array like this:

array ( 'name' => 'NAME', 'id' => 'ID', )array ( 'name' => 'NAME', 'id' => 'ID', )


However, inside the foreach loop when I'm trying to retrieve the values of 'name',
var_export($key);
returns strings:

'NAME''ID''NAME''ID'


and using
echo $key['name'] . '<br>';
would just print the first characters and give Illegal string offset warnings.

Since I am new to PHP I would like to know if there's a way to fix this and get the values of 'name'. Since it returns as strings I am unable to export the values of the 'name' field.

*Note that 'name' and 'id' refer to the fields while NAME and ID are replacement values for the values of 'name' and 'id'.

Answer

In PHP arrays can be numerically indexed, and behave like traditional arrays from other languages, or they can have string indexes and behave more like lists. You can still iterate over a list with foreach, so your inner loop first sets $key to the string 'NAME', then the string 'ID'.

To access the name property of the list directly, you can just use $key['admin_creator']['name']. In your example you can replace your inner loop with

if (isset($key['admin_creator'])) {
    echo $key['admin_creator']['name'] . '<br>';
}
Comments