php - How do I fix this illegal offset type error

PhpArrays

Php Problem Overview


I'm getting

> illegal offset type

error for every iteration of this code. Here's the code :

$s = array();
for($i = 0; $i < 20; $i++){
	$source = $xml->entry[$i]->source;
	$s[$source] += 1;    
}

print_r($s)

Php Solutions


Solution 1 - Php

Illegal offset type errors occur when you attempt to access an array index using an object or an array as the index key.

Example:

$x = new stdClass();
$arr = array();
echo $arr[$x];
//illegal offset type

Your $xml array contains an object or array at $xml->entry[$i]->source for some value of $i, and when you try to use that as an index key for $s, you get that warning. You'll have to make sure $xml contains what you want it to and that you're accessing it correctly.

Solution 2 - Php

Use trim($source) before $s[$source].

Solution 3 - Php

check $xml->entry[$i] exists and is an object before trying to get a property of it

 if(isset($xml->entry[$i]) && is_object($xml->entry[$i])){
   $source = $xml->entry[$i]->source;          
   $s[$source] += 1;
 }

or $source might not be a legal array offset but an array, object, resource or possibly null

Solution 4 - Php

There are probably less than 20 entries in your xml.

change the code to this

for ($i=0;$i< sizeof($xml->entry); $i++)
...

Solution 5 - Php

I had a similar problem. As I got a Character from my XML child I had to convert it first to a String (or Integer, if you expect one). The following shows how I solved the problem.

foreach($xml->children() as $newInstr){
        $iInstrument = new Instrument($newInstr['id'],$newInstr->Naam,$newInstr->Key);
        $arrInstruments->offsetSet((String)$iInstrument->getID(), $iInstrument);
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStevenView Question on Stackoverflow
Solution 1 - PhpzombatView Answer on Stackoverflow
Solution 2 - PhpZaferView Answer on Stackoverflow
Solution 3 - Phpbrian_dView Answer on Stackoverflow
Solution 4 - PhpByron WhitlockView Answer on Stackoverflow
Solution 5 - Phpuser8387356View Answer on Stackoverflow