Errorexception : Illegal string offset

Asked

Viewed 959 times

1

I have the following array.

$polylines = [  
     'latitude' = array(73.9289238, 83.928392832, 03.293892832),
     'longitude' = array(-122.29839238, 21.928918291, 30.203929832)
 ];

I’m trying to execute the following foreach:

 foreach ($polylines as $polyline => $valor){
  $local = $this->getLocal($polyline['latitude'][$valor], $polyline['longitude'][$valor]);

 }

I’m getting the following error message:

Errorexception : Illegal string offset 'latitude'

Excuse me the ignorance, but would anyone know why such an error is occurring? I am applying the foreach wrong way? Thanks to all

1 answer

3


Yes, you are using it wrong. This syntax makes each element of $polylines form a pair of variables called $polyline (the best name would be $chave because that is what she is) and $valor, already contains the key, so you cannot try to access it this way. Another error is that the contents of $valor is a array and not every one of his values. That is, this whole code doesn’t make sense. It looks like you want to take the values on a two-dimensional object, at least that’s how it was assembled, so you have to have two loops to do this, one for each dimension. Something like that:

$polylines = [  
    'latitude' => array(73.9289238, 83.928392832, 03.293892832),
    'longitude' => array(-122.29839238, 21.928918291, 30.203929832)
];
foreach ($polylines as $valor) {
    foreach ($valor as $item) echo $item . "\n";
    echo "\n";
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

To tell you the truth I think this data structure is wrong, I think there should be a array with pairs of latitude and longitude. That’s why I always talk: the most the developer needs to master is the data structure, is modeling. When this goes wrong all the rest of the code gets bad because it has to do wrong things to fix the initial error. In practice I think you will have to reassemble this structure to be usable the way you want, so it is much easier to mount right away. Something like that:

$polylines = array(['latitude' => 73.9289238, 'longitude' => -122.29839238],
                   ['latitude' => 83.928392832, 'longitude' => 21.928918291],
                   ['latitude' => 03.293892832, 'longitude' => 30.203929832]);
foreach ($polylines as $valor) echo $valor['latitude'] . " <=> " . $valor['longitude'] . "\n";

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Eventually you wouldn’t even have to name the second dimension and just use the position, using arrays normal.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.