[php] php - How do I fix this illegal offset type error

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)

This question is related to php arrays

The answer is


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


There are probably less than 20 entries in your xml.

change the code to this

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

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


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);
    }