D
D
DireX2015-08-26 09:33:54
PHP
DireX, 2015-08-26 09:33:54

Why does PHP throw a strange error under the same logic conditions?

Good day.
The essence of the matter is very simple. There is code that does this:

<?php

$arr = array();

$arr[] = array('Коля', 'Дима', 'Гоша');
$arr[] = array('Катя', 'Света', 'Яна');

for($i = 0; $i < 10; $i++){
  //unset($result);
  foreach ($arr as $key => $value) {
    $result[$i][$key]['names'] = $value; 
  }


  $result = json_encode($result);
  print_r($result);
}

This code will throw an error.
And there is the same code, only before foreach we delete the already defined array
<?php

$arr = array();

$arr[] = array('Коля', 'Дима', 'Гоша');
$arr[] = array('Катя', 'Света', 'Яна');

for($i = 0; $i < 10; $i++){
  unset($result);
  foreach ($arr as $key => $value) {
    $result[$i][$key]['names'] = $value; 
  }


  $result = json_encode($result);
  print_r($result);
}

This is the working code, there is no error.
In fact, the first and second codes are absolutely no different, but the result is obvious.
Can you help me understand what this behavior is?
PHP 5.5.9 || 5.4.44
Fatal error: Cannot use string offset as an array in /home/direx/wtf.php on line 11

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vyacheslav Ovchinnikov, 2015-08-26
@xDireX

It's all about this line:
When the for loop goes to the second round - $result is no longer an array, and therefore it can not be accessed like this: $result[$i][$key]['names']

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question