user3764895 user3764895 - 7 months ago 30
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){
foreach ($key['admin_creator'] as $key){
//echo $key['name'] . '<br>';

The entire thing works and
would return an array up until the last foreach loop. Before entering the last foreach loop,
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',
returns strings:


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'.


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>';