Illegal string offset php ошибка

You’re trying to access a string as if it were an array, with a key that’s a string. string will not understand that. In code we can see the problem:

"hello"["hello"];
// PHP Warning:  Illegal string offset 'hello' in php shell code on line 1

"hello"[0];
// No errors.

array("hello" => "val")["hello"];
// No errors. This is *probably* what you wanted.

In depth

Let’s see that error:

Warning: Illegal string offset ‘port’ in …

What does it say? It says we’re trying to use the string 'port' as an offset for a string. Like this:

$a_string = "string";

// This is ok:
echo $a_string[0]; // s
echo $a_string[1]; // t
echo $a_string[2]; // r
// ...

// !! Not good:
echo $a_string['port'];
// !! Warning: Illegal string offset 'port' in ...

What causes this?

For some reason you expected an array, but you have a string. Just a mix-up. Maybe your variable was changed, maybe it never was an array, it’s really not important.

What can be done?

If we know we should have an array, we should do some basic debugging to determine why we don’t have an array. If we don’t know if we’ll have an array or string, things become a bit trickier.

What we can do is all sorts of checking to ensure we don’t have notices, warnings or errors with things like is_array and isset or array_key_exists:

$a_string = "string";
$an_array = array('port' => 'the_port');

if (is_array($a_string) && isset($a_string['port'])) {
    // No problem, we'll never get here.
    echo $a_string['port'];
}

if (is_array($an_array) && isset($an_array['port'])) {
    // Ok!
    echo $an_array['port']; // the_port
}

if (is_array($an_array) && isset($an_array['unset_key'])) {
    // No problem again, we won't enter.
    echo $an_array['unset_key'];
}


// Similar, but with array_key_exists
if (is_array($an_array) && array_key_exists('port', $an_array)) {
    // Ok!
    echo $an_array['port']; // the_port
}

There are some subtle differences between isset and array_key_exists. For example, if the value of $array['key'] is null, isset returns false. array_key_exists will just check that, well, the key exists.

Warning: illegal string offset in PHP seven is a common error that occurs when you try to use a string like a PHP array. This error can arise from typographical errors or a misunderstanding of the limitations of array operations on a string and that’s what this article will clear up for you.Warning Illegal String Offset

As you read this article, we’ll show you code examples with code comments that explain what’s wrong with the code and why it won’t work. Now, grab your computer and launch your code editor because you’re about to learn how to fix illegal string offset in PHP.

Contents

  • Why PHP Reports an Illegal String Offset in Your Code
    • – You Accessed a String Like an Array
    • – You Initialize a Variable as a String
    • – Your Multidimensional Array Has a String Element
    • – Your Variable Contains Json Encoded Data
  • How To Stop Illegal String Offsets in PHP
    • – Use Conditional Statements
    • – Change the Variable to an Array
    • – Use “is_array()” When You Loop Multidimensional Arrays
    • – Decode the Json String Before You Access It
  • Conclusion

Why PHP Reports an Illegal String Offset in Your Code

PHP Reports an illegal string offset in your code because of the following:

  • You accessed a string like an array
  • You initialize a variable as a string
  • Your multidimensional array has a string element
  • Your variable contains JSON encoded data

– You Accessed a String Like an Array

You can do some array-like operations on a string in PHP, but you’ll run into errors if you try to use the string like a full PHP array. In the following code, you’re telling PHP to return the element at the “string” offset. This is illegal because that offset does not exist in the string, and PHP seven will raise a warning. A similar approach will cause the illegal string offset CodeIgniter warning.

<?php

$sample_variable = “This is a string!”;

// Access it like an array? It won’t work!

echo $sample_variable[‘string’];

?>

– You Initialize a Variable as a String

Array initialization as a string will lead to a PHP seven warning when you perform other array operations on the string. That’s because it’s not allowed and it arises as a result of forgetfulness or typographical errors. In the following code, we initialized the “array” as a string, as a result, it’ll lead to the illegal string offset PHP 7 warning.

<?php

// This is a string!, or do you want an

// array?

$sample_variable = ”;

// A mistake to assign an index to the string

// leads to an error!

$sample_variable[“why?”] = “take that!”;

// The code will not reach this point!

print_r($sample_variable);

?>

The following is another example that has an array that does not exist in the function. That’s because the variable that should hold the array is a string.

<?php

function show_internal_array_elements() {

// This is a string and not an array.

$array = ”;

$array[‘first_element’] = ‘Hello’;

$array[‘second_element’] = ‘World’;

return print_r($array);

}

show_internal_array_elements();

?>

– Your Multidimensional Array Has a String Element

Multidimensional arrays that contain string as an array element will lead to the warning: illegal string offset php foreach warning. This happens because when you loop over this array, you’ll check the array keys before you proceed.Warning Illegal String Offset Causes

But a string in-between these arrays will not have a “key” and the following is an example.

<?php

// Sample names in a multidimensional array

$sample_names = [

[“scientist” => “Faraday”],

“”,

[“scientist” => “Rutherford”]

];

// There is a string in the “$sample_names”

// multidimensional array. So, the result

// in a PHP illegal string offset.

foreach ($sample_names as $values) {

echo $values[“scientist”]. “n”;

}

?>

– Your Variable Contains Json Encoded Data

You can’t treat JSON encoded data like an array and if you do, you’ll get a warning about an illegal offset in PHP seven. You’ll run into this error when working with Laravel and you attempt to send an object to the server. In the following code, we used an array operation on JSON encoded data, and the result is an illegal offset warning.

<?php

// An associative array

$student_scores = array(“Maguire”=>65, “Kane”=>80, “Bellingham”=>78, “Foden”=>90);

// JSON encode the array

$encode_student_scores = json_encode($student_scores, true);

// This will not work! You’ll get an illegal offset

// warning.

echo $encode_student_scores[‘Maguire’];

?>

How To Stop Illegal String Offsets in PHP

You can stop illegal string offset in your PHP code using any of the following methods:

  • Use conditional statements
  • Change the variable to an array
  • Use “is_array()” when you loop multidimensional arrays
  • Decode the JSON string before you access it

– Use Conditional Statements

Conditional statements will not get rid of the illegal offset warning in your code, but they’ll ensure PHP does not show it at all. In the following, we revisit our first example and we show how a conditional statement can show custom error messages. We use the PHP “is_array()” function to check if the variable is an array before doing anything.

<?php

$sample_variable = “This is a string!”;

// Use a combination of “is_array()” and “isset()”

// to check if “$sample_variable” is an array.

// If true, only then we print the key.

if (is_array($sample_variable) && isset($sample_variable[‘string’])) {

echo $sample_variable[‘string’];

} else {

echo “Variable is not an array or the array key does not exists.n”;

}

// Here, we use “is_array()” and “array_key_exists”

// for the check.

if (is_array($sample_variable) && array_key_exists($sample_variable[‘string’], $sample_variable)) {

echo $sample_variable[‘string’];

} else {

echo “Second response: Variable is not an array or the array key does not exist”;

}

?>

– Change the Variable to an Array

You can’t treat strings like a full PHP array, but mistakes do happen in programming. The following is the correct example of the code that initialized a string and then performed an array-like operation.Warning Illegal String Offset Fixes

The correction is to change the string to an array using “array()” or square bracket notation. This tells PHP that the variable is an array and it will stop the illegal string offset PHP array warning.

<?php

// Fix1: Convert “$sample_variable” into an

// Array

$sample_variable = [];

// You can also use the “array()” function

// itself as shown below:

// $sample_variable = array();

// Now, this will work!

$sample_variable[“why?”] = “take that!”;

// This time, you’ll get the content of the array!

print_r($sample_variable);

?>

Also, the following is a rewrite of the function that shows the same warning. This time, we ensure the variable is an array and not a string.

<?php

function show_internal_array_elements() {

// Change it to an array and everything

// will work

$array = [];

$array[‘first_element’] = ‘Hello’;

$array[‘second_element’] = ‘World’;

return print_r($array);

}

show_internal_array_elements();

?>

– Use “is_array()” When You Loop Multidimensional Arrays

You should confirm if an element of your multidimensional array is an array using the “is_array()” function in PHP. In the following, we’ve updated the code that showed the PHP illegal offset warning earlier in the article. So, when you loop through elements of the array, you can check if it’s an array before you print its value.

<?php

// Sample names in a multidimensional array

$sample_names = [

[“scientist” => “Faraday”],

“”,

[“scientist” => “Rutherford”]

];

// Now, the “foreach()” loop has the

// is_array() function that confirms if

// the array element is an array before

// printing its value.

foreach ($sample_names as $values) {

if (is_array($values)) {

echo $values[“scientist”]. “n”;

} else {

echo “Not an array.n”;

}

}

/* Expected output:

Faraday

Not an array.

Rutherford

*/

?>

– Decode the Json String Before You Access It

If you have a JSON encoded string, decode it before treating it like an array. If you’re working with Laravel, this will prevent the illegal string offset Laravel warning. The following is not a Laravel code but you can borrow the same idea to fix the warning in Laravel. The idea is to decode JSON encoded data using “json_decode()”.

<?php

// An associative array

$student_scores = array(“Maguire”=>65, “Kane”=>80, “Bellingham”=>78, “Foden”=>90);

// JSON encode the array

$encode_student_scores = json_encode($student_scores, true);

// Fix: Decode the json before you do

// anything else. Don’t forget to include the

// second argument, ‘true’. This will allow

// it to return an array and not an Object!

$JSON_decode_student_scores = json_decode($encode_student_scores, true);

// Now, this will work as expected!.

print_r($JSON_decode_student_scores[‘Maguire’]);

?>

Conclusion

This article shows you why PHP seven shows a warning about an illegal string offset in your code. Later, we explained techniques that you can use taking note of the following:

  • When you treat a string like an array, it can lead to the PHP warning about illegal offset.
  • Array-like operations on JSON encoded data will cause an illegal offset warning in PHP seven.
  • Use the PHP “is_array()” function to check if a variable or an element is an array before working on it.
  • Use conditional statements to show a custom message in place of the illegal string offset warning in PHP seven.
  • Illegal string offset meaning depends on your code, it’s either you’re treating an array like a string or you did not confirm if your variable is an array.

Everything that we discussed shows that you should not always treat strings like a PHP array. With your newly found knowledge, you know how to avoid PHP warnings about illegal offsets in your code.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything


Photo from Unsplash

The PHP warning: Illegal string offset happens when you try to access a string type data as if it’s an array.

In PHP, you can access a character from a string using the bracket symbol as follows:

$myString = "Hello!";

// 👇 access string character like an array
echo $myString[0]; // H
echo $myString[1]; // e
echo $myString[4]; // o

When you try to access $myString above using an index that’s not available, the PHP warning: Illegal string offset occurs.

Here’s an example:

$myString = "Hello!";

// 👇 these cause illegal offset
echo $myString["state"]; // PHP Warning:  Illegal string offset 'state' in..
echo $myString["a"]; // PHP Warning:  Illegal string offset 'a' in ..

To resolve the PHP Illegal string offset warning, you need to make sure that you are accessing an array instead of a string.

To check if you’re actually accessing an array, you can call the is_array() function before accessing the variable as follows:

$myArray = [
    "state" => true,
    "port" => 1331,
];

// 👇 check where myArray is really an array
if (is_array($myArray)) {
    echo $myArray["port"];
    echo $myArray["L"];
}

This warning will also happen when you have a multi-dimensional PHP array where one of the arrays is a string type.

Consider the following example:

$rows = [
    ["name" => "John"],
    "",
    ["name" => "Dave"]
];

foreach ($rows as $row) {
    echo $row["name"]. "n";
}

The $rows array has a string at index one as highlighted above.

When you loop over the array, PHP will produce the illegal string offset as shown below:

John
PHP Warning:  Illegal string offset 'name' in ...

Dave

To avoid the warning, you can check if the $row type is an array before accessing it inside the foreach function:

foreach ($rows as $row) {
    if(is_array($row)){
        echo $row["name"]. "n";
    }
}

When the $row is not an array, PHP will skip that row and move to the next one.

The output will be clean as shown below:

When you see this warning in your code, the first step to debug it is to use var_dump() and see the output of the variable:

From the dump result, you can inspect and see if you have an inconsistent data type like in the $rows below:

array(3) {
  [0]=>
  array(1) {
    ["name"]=>
    string(4) "John"
  }
  [1]=>
  string(0) ""
  [2]=>
  array(1) {
    ["name"]=>
    string(4) "Dave"
  }
}

For the $rows variable, the array at index [1] is a string instead of an array.

Writing an if statement and calling the is_array() function will be enough to handle it.

And that’s how you solve the PHP warning: Illegal string offset. Good luck! 👍

За последние 24 часа нас посетили 12437 программистов и 897 роботов. Сейчас ищут 749 программистов …


  1. abutan

    С нами с:
    25 мар 2019
    Сообщения:
    10
    Симпатии:
    0

    Доброго времени суток всем.
    Проблема вот какая — есть вот такой массив

    1.             [name] => Желаемая высота забора (м)
    2.             [answers] => ответ 2|ответ 2.2

    начинаю его обрабатывать

    1. foreach ($calc as $item => $value) {
    2.     // и тут выполняю разные действия  …
    3.    $mas_answers = explode(‘|’, $value[‘answers’]);

    И всюду где использую $value[‘name’] или ‘answers’ или ‘multiple_ans’ получаю Illegal string offset ‘name’ или ‘answers’ и тд
    Сам смысл ошибки я понимаю. Вместо массива оказалась строка, но , блин $value имеет вот такой вид

    1.     [name] => Желаемая высота забора (м)
    2.     [answers] => ответ 2|ответ 2.2

    Как же мне тогда к ним обращаться ?
    Подскажите в чем я неправ.
    Заранее благодарен.


  2. Artur_hopf

    Artur_hopf
    Активный пользователь

    С нами с:
    7 май 2018
    Сообщения:
    2.266
    Симпатии:
    405

    Покажи массив свой $calc.

    Что то ты долго, не массив у тебя то что ты там написал, вот так можно:

    1.       ‘name’ => ‘Желаемая высота забора (м)’,
    2.       ‘answers’ => ‘ответ 2|ответ 2.2’,
    3. foreach ($calc as $item => $value) {
    4.   // и тут выполняю разные действия  …


  3. abutan

    С нами с:
    25 мар 2019
    Сообщения:
    10
    Симпатии:
    0

    1.             [name] => Желаемая высота забора (м)
    2.             [answers] => ответ 2|ответ 2.2

  4. Тс, не смущает тот факт, что ты в конце концов, в каждой своей залитой данными переменные, результат получишь по ласт проходу массива?
    — Добавлено —

    1. foreach ( $a AS $b ) { $c = $b; }

    — Добавлено —
    Что получим ? 1 ? 2 3 ?


  5. abutan

    С нами с:
    25 мар 2019
    Сообщения:
    10
    Симпатии:
    0

    В данный момент меня смущает ошибка
    Illegal string offset


  6. Artur_hopf

    Artur_hopf
    Активный пользователь

    С нами с:
    7 май 2018
    Сообщения:
    2.266
    Симпатии:
    405

    @abutan ну не массив у тебя это потому что.


  7. abutan

    С нами с:
    25 мар 2019
    Сообщения:
    10
    Симпатии:
    0

    А можно как то поразвернутей )))
    Как мне к этому «не массиву» обращаться


  8. sobachnik

    Сложно угадать, не видя всей картины. Ну, например, возможно вы обращаетесь к переменным не внутри цикла { … } а где-то вообще в другом месте. Мы же не знаем :)

    После того, как вы написали

    1. $mas_answers = explode(‘|’, $value[‘answers’]);

    Массив ответов появился в переменной $mas_answers, а в $value[‘answers’] — там как была строка текста, так и осталась.

    И да, а что будет, если пользователь в комментарии поставит символ вертикальной черты | ? :))) В PHP есть штатные функции для преобразования массива в строку (для сохранения в базе данных или в файле) и для обратного преобразования строки в массив. При этом, PHP позаботится о том, чтобы не зависимо от пользовательского ввода у вас элементы массива остались такими, какими должны быть. Например, посмотрите функции
    https://www.php.net/manual/ru/function.serialize.php
    https://www.php.net/manual/ru/function.unserialize.php


  9. abutan

    С нами с:
    25 мар 2019
    Сообщения:
    10
    Симпатии:
    0

    1. <form action=»#» method=»post»>
    2.             foreach($calc as $index => $value){
    3.                 $mas_answers = explode(‘|’, $value[‘answers’]);
    4.                 echo ‘<div class=»tabs_block» tabid=»‘.$index.‘»‘;
    5.                     echo ‘ style=»display:none;»‘;
    6.                          <input class=»form-control» name=»question» type=»text» id=»response_options» placeholder=»» value=»‘.addslashes($value[‘name’]).‘» autocomplete=»off»><br>
    7.                          <span class=podkomment >Например: «Выберите тип материала»</span>
    8.                <h2>Варианты ответов:</h2>’;
    9.                 if(count($mas_answers)==0){
    10.                     echo ‘<div class=»input_form answer_input» attr=»1″ quest=»‘.$index.‘»>
    11.                  <p>1.</p><a href=»javascript:void(0);» class=»answer_remove»></a>
    12.                      <input class=»form-control» type=»text» name=»answer» autocomplete=»off» placeholder=»Вариант ответа #1″ value=»»>
    13.                     foreach($mas_answers as $nom=>$answers){
    14.                         echo ‘<div class=»input_form answer_input» attr=»‘.($nom_real).‘» quest=»‘.($nom_real).‘»>
    15.                      <p>’.($nom_real).‘.</p><a href=»javascript:void(0);» class=»answer_remove»></a>
    16.                          <input class=»form-control» type=»text» name=»answer» autocomplete=»off» placeholder=»Вариант ответа #’.($nom_real).‘» value=»‘.$answers.‘»>
    17.                 echo ‘<a href=»javascript:void(0);» class=»right_add_content»>Добавить ещё</a>
    18.              <h2>Возможность выбора:</h2>
    19.              <input type=»radio» name=»multiple_ans» id=»one’.$index.‘» autocomplete=»off» value=»0″‘;
    20.                 if($value[‘multiple_ans’]==0) echo ‘ checked=»checked»‘;
    21.                 echo ‘><label for=»one’.$index.‘»>Можно выбрать только один ответ (radiobutton)</label><br>
    22.              <input type=»radio» name=»multiple_ans» id=»two’.$index.‘» autocomplete=»off» value=»1″‘;
    23.                 if($value[‘multiple_ans’]==1) echo ‘ checked=»checked»‘;
    24.                 echo ‘><label for=»two’.$index.‘»>Можно выбрать несколько вариантов (checkbox)</label><br>
    25.              <input type=»radio» name=»multiple_ans» id=»thr’.$index.‘» autocomplete=»off» value=»2″‘;
    26.                 if($value[‘multiple_ans’]==2) echo ‘ checked=»checked»‘;
    27.                 echo ‘><label for=»thr’.$index.‘»>Нужно вводить данные (input)</label>


  10. sobachnik

    Чтобы совсем всё понятно было — после <?php и перед foreach добавьте ещё строку

    и опубликуйте здесь, что оно выведет


  11. abutan

    С нами с:
    25 мар 2019
    Сообщения:
    10
    Симпатии:
    0

    1. array(2) { [1]=> array(3) { [«name»]=> string(47) «Желаемая высота забора (м)» [«answers»]=> string(0) «» [«multiple_ans»]=> string(1) «2» } [2]=> array(3) { [«name»]=> string(13) «вопрос2» [«answers»]=> string(27) «ответ 2|ответ 2.2» [«multiple_ans»]=> string(1) «0» } }

  12. Хотите прикол ?
    начало все норм кроме

    после string перебираем в foreach

    1. foreach($mas_answers as $nom=>$answers){

  13. sobachnik

    @abutan Этот код с такими исходными данными (таким массивом $calc) — должен работать без ошибок. Для эксперимента, запустил его у себя, создав массив перед перебором в цикле. У меня этот код из этого массива успешно сгенерировал html.
    Посмотрите внимательно на текст сообщения об ошибке, которую выдаёт PHP — там указывается файл и номер строки, на которой произошла ошибка. Возможно, она происходит где-то в другом месте?

    У вас есть ошибка в вёрстке — в самом начале вы открываете <form> за пределами цикла, а закрываете </form> внутри цикла (то есть открывающий тег будет один, а закрывающих будет столько же, сколько элементов в массиве $calc). Но ошибка вёрстки никак не влияет на появление сообщения «Illegal string offset»

  14. @sobachnik

    1. foreach ( $a AS $b ) { $c = $b; }

    — Добавлено —
    пусть покажет полностью ошибку


  15. abutan

    С нами с:
    25 мар 2019
    Сообщения:
    10
    Симпатии:
    0

    Там все немного сложнее. Эта форма вложена во вторую форму. И этот весь код работает. Вполне корректно, я получаю в ответе то что мне надо. Проблема появляется когда я пытаюсь отправить результаты в контролер по ajax.

    1. form.submit(function(e) {
    2.         let user_id = $(‘input[name=»user_id»]’).val();
    3.         let url = form.attr(‘action’);
    4.         $(‘.tabs_content_block .tabs_block’).each(function(a,obj){
    5.             let name = $(obj).find(‘input[name=»question»]’).val();
    6.             let answers = $(obj).find(‘input[name=»answer»]’).map( function(){ if ( $(this).val()!=» ) return $(this).val().replace(/|/g,‘ ‘);} ).get().join(‘|’);
    7.             let multiple_ans = $(obj).find(‘input[name=»multiple_ans»]:checked’).val();
    8.             post_data[a] = { ‘name’:name, ‘answers’:answers,‘multiple_ans’:multiple_ans };
    9.         post_data = {‘calc’:post_data, ‘user_id’: user_id};
    10.             done: function (response) {
    11.             error: function(result) {
    12.                 alert(‘Error: ‘+result[‘status’]+‘: ‘+result[‘responseText’]);

    Вот в этот момент и вылетает

    1. Error: 500: <pre>PHP Warning 'yiibaseErrorException' with message 'Illegal string offset 'answers''
    2. in /var/www/html/frontend/views/widgetuser/calc.php:53
    3. #0 /var/www/html/frontend/views/widgetuser/calc.php(53): yiibaseErrorHandler-&gt;handleError(2, 'Illegal string …', '/var/www/html/f…', 53, Array)
    4. #1 /var/www/html/vendor/yiisoft/yii2/base/View.php(348): require('/var/www/html/f…')
    5. #2 /var/www/html/vendor/yiisoft/yii2/base/View.php(257): yiibaseView-&gt;renderPhpFile('/var/www/html/f…', Array)
    6. #3 /var/www/html/vendor/yiisoft/yii2/base/View.php(156): yiibaseView-&gt;renderFile('/var/www/html/f…', Array, Object(frontendcontrollersWidgetuserController))
    7. #4 /var/www/html/vendor/yiisoft/yii2/base/Controller.php(384): yiibaseView-&gt;render('calc', Array, Object(frontendcontrollersWidgetuserController))
    8. #5 /var/www/html/frontend/controllers/WidgetuserController.php(150): yiibaseController-&gt;render('calc', Array)
    9. #6 [internal function]: frontendcontrollersWidgetuserController-&gt;actionCalc()
    10. #7 /var/www/html/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
    11. #8 /var/www/html/vendor/yiisoft/yii2/base/Controller.php(157): yiibaseInlineAction-&gt;runWithParams(Array)
    12. #9 /var/www/html/vendor/yiisoft/yii2/base/Module.php(528): yiibaseController-&gt;runAction('calc', Array)
    13. #10 /var/www/html/vendor/yiisoft/yii2/web/Application.php(103): yiibaseModule-&gt;runAction('widgetuser/calc', Array)
    14. #11 /var/www/html/vendor/yiisoft/yii2/base/Application.php(386): yiiwebApplication-&gt;handleRequest(Object(yiiwebRequest))
    15. #12 /var/www/html/frontend/web/index1.php(36): yiibaseApplication-&gt;run()


  16. sobachnik

    @Babka_Gadalka
    Я не понимаю, что вы хотите этим сказать или показать.

    Приведённый вами код приводит к ошибке
    Warning: Invalid argument supplied for foreach()
    поскольку в первом цикле, после его завершения, переменной $c присваивается значение 4 (число), а цикл foreach не может «перебрать» число.

    Если вы намекаете, что автор сперва в одном цикле создаёт переменную $mas_answers, а потом где-то в другом месте (после завершения первого цикла) пытается её использовать — то это не так. В приведённом автором коде видно, что массивы вложены друг в друга, а не расположены отдельно независимо друг от друга. То есть если комбинировать код автора и ваш — получится что-то типа

  17. Ой, вижу :D


  18. abutan

    С нами с:
    25 мар 2019
    Сообщения:
    10
    Симпатии:
    0

    Ага.
    Вот именно с этого я и начал

    1. $mas_answers = explode(‘|’, $value[‘answers’]);


  19. sobachnik

    Далее постепенно подниматься по коду вверх и смотреть, как и где создаются переменные, откуда берутся их значения.

    Если это тот самый код, который вы публиковали выше, значит в массив $calc попадают другие данные именно когда вы

    То есть вам нужно загрузить в браузере страницу с этой формой, после чего (пока страница открыта, но форма ещё не отправлена) вставить в код перед foreach строку

    После этого отправляйте форму и смотрите, что выведет var_dump().
    То есть суть в том, что нужно посмотреть содержимое массива именно в момент ошибки, а не тогда, когда генерация страницы проходит успешно.


  20. abutan

    С нами с:
    25 мар 2019
    Сообщения:
    10
    Симпатии:
    0

    Все переменные пришли из контролера, выбранные из бд. Так что ничего не меняется в var_dum. Возможно к сожалению.


  21. sobachnik

    Ошибка происходит в PHP коде, при обработке вашего ajax-запроса. Нужно, чтобы этот var_dump отработал именно тогда, когда происходит ошибка, а не тогда, когда страница нормально загружается. То есть нужно смотреть var_dump именно при обработке вашего ajax-запроса. И я выше написал, как это сделать, прочитайте, пожалуйста, внимательно.
    — Добавлено —
    Если при открытии страницы ошибки нет, а при ответе на ajax-запрос ошибка происходит — значит что-то меняется 100% :) Либо там выполняется другой код, либо в него приходят другие данные. А как иначе-то?


  22. abutan

    С нами с:
    25 мар 2019
    Сообщения:
    10
    Симпатии:
    0

    Огромное спасибо.
    Нашел таким образом опечатку в контролере.
    Еще раз спасибо.

While you are utilizing PHP, have you ever met the Warning: Illegal string offset yet? If that is all you are facing and trying to solve, don’t worry because we are here to help you to address the trouble.

What causes the Warning: Illegal string offset?

Let’s take a look at the following example so that we can explain it in a clear way.

You have the code:

Array
(
[host] => 127.0.0.1
[port] => 11211
)

And when you try to access it, there will be the warning:

print $memcachedConfig['host'];
print $memcachedConfig['port'];

Warning: Illegal string offset 'host' in ....
Warning: Illegal string offset 'port' in ...

In this case, you are trying to use a string as if it was a full array. In other words, you think the code you are using is an array, but in fact, it is a string. This is not allowed. As a result, you can not print and you will get the warning: Illegal string offset in PHP.

Besides that, you can also face the warning if you have a multi-dimensional PHP array in which there will have a string instead of an array.

So, now, we will show you 2 solutions to tackle the 2 reasons for the issue mentioned above.

How to fix the Warning: Illegal string offset?

In the first case, in order to solve the warning: Illegal string offset or make it disappears, you need to ensure that you are accessing an array instead of a string. All you need to do now is check whether you are accessing an array by calling the is_array() and the isset function before you access the variable. For instance:

$a_string = "string";
$an_array = array('port' => 'the_port');




if (is_array($a_string) && isset($a_string['port'])) {
// No problem, we'll never get here.
echo $a_string['port'];
}




if (is_array($an_array) && isset($an_array['port'])) {
// Ok!
echo $an_array['port']; // the_port
}




if (is_array($an_array) && isset($an_array['unset_key'])) {
// No problem again, we won't enter.
echo $an_array['unset_key'];
}

Moreover, in case you are troubled with the PHP warning: Illegal string offset because of the second reason, you can also check where the string is with the help of is_array() and var_dump(). Now, let’s move on to another example:

$rows = [
["name" => "John"],
"",
["name" => "Dave"]
];




foreach ($rows as $row) {
echo $row["name"]. "n";
}

In this situation, the $rows array contains a string in line 3. That is the reason why loop over the array, there will be a PHP warning. Therefore, before accessing the array inside the foreach function, you need to check the $row type:

foreach ($rows as $row) {
if(is_array($row)){
echo $row["name"]. "n";
}
}

If the $row is not an array, PHP will ignore the row and then move to the next one. As a result, you will receive the output:

John
Dave

Next, it’s time for you to fix it by using var_dump() to see the output of the variable:

var_dump($rows);

Now, in the dump result, you can check whether a string remains in your $rows or not:

array(3) {
[0]=>
array(1) {
["name"]=>
string(4) "John"
}
[1]=>
string(0) ""
[2]=>
array(1) {
["name"]=>
string(4) "Dave"
}
}

It is noticed that the [1] is not an array, it is a string. Hence, you need to use the “if” statement and call the is_array() function to deal with this issue.

Closing thoughts

All in all, we hope that the blog today will help you address the Warning: Illegal string offset in PHP effectively. If you meet the same problem and have another greater solution, don’t forget to share it with us by leaving your comment below. We will be happy about it.

Furthermore, in case you have an intention to give your site a new and fresh appearance, don’t hesitate to visit our site, then get the best free WordPress themes and Joomla 4 Templates. We hope you will like them.

  • Author
  • Recent Posts

Lt Digital Team (Content &Amp; Marketing)

Welcome to LT Digital Team, we’re small team with 5 digital content marketers. We make daily blogs for Joomla! and WordPress CMS, support customers and everyone who has issues with these CMSs and solve any issues with blog instruction posts, trusted by over 1.5 million readers worldwide.

Lt Digital Team (Content &Amp; Marketing)

Понравилась статья? Поделить с друзьями:
  • Illegal start of type java ошибка
  • Illegal opcode hp proliant ошибка
  • Illegal offset type in ошибка
  • Illegal new face 3d max ошибка
  • Illegal devices please use genuine как исправить ошибку подключения