Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - How do I fix this illegal offset type error

Tags:

arrays

php

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) 
like image 833
Steven Avatar asked Apr 28 '10 19:04

Steven


2 Answers

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.

like image 78
zombat Avatar answered Oct 03 '22 02:10

zombat


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

like image 36
Zafer Avatar answered Oct 03 '22 04:10

Zafer