Ошибка trying to access array offset on value of type int

I have a problem with the error message «Trying to access array offset on the value of type int» I use PHP version 7.4, as I see on the web :

Array-style access of non-arrays

bool, int, float or resource as an array (such as $null[«key»]) will now generate a notice.

Code is:

 <?php
        foreach($gdata_worksheets As $key => $value ){
            //$key="1361298261";
        ?>
            <option value="<?php echo strToHex($key); ?>"<?php echo $key == $gdata->worksheet_id ? ' selected="selected"' : ''?>><?php echo htmlentities($value, ENT_QUOTES, 'UTF-8');?></option>
            



function strToHex($string){

$hex = '';
for ($i=0; $i<strlen($string); $i++){
    $ord = ord($string[$i]);
    $hexCode = dechex($ord);
    $hex .= substr('0'.$hexCode, -2);
}
return strToUpper($hex);

}

How solve this, any idea?

Regards

asked Dec 28, 2021 at 9:50

mirec's user avatar

mirecmirec

1171 gold badge1 silver badge6 bronze badges

1

$key is probably not a string, you can use gettype() to check.

You can access to number digits with substr() :

for ($i=0; $i<strlen($string); $i++){
    $ord = ord(substr($string, $i, 1));

If you prefer use array-access you must cast $string to (string) :

function strToHex($string){
    $string = (string)$string;

A final propal could be :

function strToHex($string)
{
    $result = '';
    $n = strlen($string);
    for ($i = 0; $i < $n; $i++) {
        $c = substr($string, $i, 1);
        $c = ord($c);
        $result .= sprintf('%02X', $c);
    }
    return $result;
}

echo strToHex(1234); // 31323334
echo strToHex('Yop!'); // 596F7021

answered Dec 28, 2021 at 10:18

JCH77's user avatar

JCH77JCH77

1,05911 silver badges11 bronze badges

3

Миграция с PHP5 на PHP7 и PHP8: что чаще всего приходится править в исходниках

Если не считать необходимого теперь перехода с MySQL на MySQLi и борьбы с Warning: A non-numeric value encountered, есть ещё несколько типовых проблем при миграции скриптов с PHP 5.X (особенно если исходная версия ниже 5.3) на PHP 7.3 — 7.4, а позднее и на PHP 8. Попробую приспособить для описания решений эту заметку, если ещё всплывёт подобное.

Для проверки фрагментов кода предполагалось, что в его начале указана директива

 error_reporting (E_ALL);
Уведомление Trying to access array offset on value of type null/bool/int

Часто возникает при использовании синтаксиса обращения к элементу массива на других типах данных. Пример:

$a = false;
var_dump($a['somekey']);
// PHP 7.3: 
// NULL
// 
// PHP 7.4:
// Notice: Trying to access array offset on value of type bool in Command line code on line ...

Так бывает, например, если функция может возвращать массив в нормальном случае и false/null в случае ошибки, а дальше вверх по стеку информация о false/null теряется и этот случай не обрабатывается отдельно.

Решение — проверять с помощью is_array, является ли объект массивом.

Применение функции mysql_real_escape_string

…которой традиционно «обезопасивали» хранимые в базе данных строки от SQL-инъекций.

было: mysql_real_escape_string($s)

надо: mysqli_real_escape_string ($id,$s), где $id — идентификатор соединения MySQLi. Или хотя бы addslashes($s) — если нужно только экранировать «опасные» для SQL-запроса кавычки.

Перебор массива с помощью list и each

было: while (list(,$var) = each($params)) {

надо: foreach ($params as $var) {

или же: while (list($num,$var) = each($params)) {

а теперь: foreach ($params as $num=>$var) {

— если массив перебирается как ассоциативный и/или нужны ключи его элементов.

Модификатор /e функции preg_replace

было:

$text = preg_replace('~([0-9]+)^([0-9]+)~e', 'pow("\1", "\2")', $text); //вычислить a^b

надо:

$text = preg_replace_callback('~([0-9]+)^([0-9]+)~',

function ($m) { return pow($m[1], $m[2]); }, $text); //вычислить a^b

— то есть, через callback-функцию.

Проблема с подключаемыми графическими шрифтами GD

было:

$bbox=imagettfbbox ($f,0,'arial.ttf','String');

надо:

$font = dirname(__FILE__) . '/arial.ttf';

$bbox=imagettfbbox ($f,0,$font,'String');

— если фонт лежит в папке скрипта, как обычно и бывает.

То же самое с imageTtfText, например:

$font = dirname(__FILE__) . '/Roboto-Bold.ttf';
imageTtfText($myimg, $size, $angle, $j, 30, $c, $font, $z);
error_reporting(0) и подобное

Многие разработчики привыкли решать проблему с предупреждениями и даже сообщениями об ошибках просто выключая сообщения о них. При миграции скриптов это приводит к «загадочным белым экранам» вместо содержимого. Лучше всего вообще не трогать включённое в новых версиях протоколирование ошибок по умолчанию, а все вызовы функции error_reporting приводить к виду, указанному в начале статьи.

Строковые функции

Начиная с версии PHP 5.6 кодировкой по умолчанию стала кодировка Юникода UTF-8, соответственно, вместо прежних «си-подобных» строковых функций теперь лучше использовать их многобайтовые аналоги.

Наиболее часто приходится менять:

  • вместо strlen($s) писать mb_strlen($s,'UTF-8');
  • вместо strpos ($haystack,$needle,0) писать mb_strpos ($haystack,$needle,0,'UTF-8');
  • вместо strstr ($haystack,$needle,false) писать mb_strstr ($haystack,$needle,false,'UTF-8');
  • вместо substr ($string,$start,$length) писать mb_substr ($string,$start,$length,'UTF-8')

…и т.д., принцип, думаю, понятен. Будьте внимательны, проверяя, есть ли для функции многобайтовый аналог.

Для «бинарно безопасных» функций strcmp / strcasecmp, к примеру, таковых нет, а сравнение всё равно не работает:

<?php
 $s1="Привет";
 $s2="привет";
 echo strcasecmp($s1,$s2); //-32
?>

и нужно делать так:

<?php
 function mb_strcasecmp($str1, $str2, $encoding = null) {
  if (null === $encoding) { $encoding = mb_internal_encoding(); }
  return strcmp(mb_strtoupper($str1, $encoding), mb_strtoupper($str2, $encoding));
 }

 $s1="Привет";
 $s2="привет";
 echo mb_strcasecmp($s1,$s2,'UTF-8'); //0
?>

С другой стороны, как видно из примера, для strtoupper и strtolower эти аналоги есть.

Применение array_key_exists к объекту, а не к массиву

Теперь нельзя применять array_key_exists к объектам классов (а можно только к массивам). Неправильно:

 class foo {
  public $a, $b;
 };
 $bar = new foo();
 echo (array_key_exists('a',$bar) ? 'yes' : 'no'); //deprecated

Правильно:

  echo (property_exists($bar,'a') ? 'yes' : 'no'); //yes

Итак, 8-я версия, вышедшая в ноябре-2020, теперь есть и в составе XAMPP, ниже, вероятнее всего, будут добавляться исправления для PHP8, хотя и для версии 7 всё написанное выше остаётся в силе.

Отмечу, что в сборке PHP 8.0.0 с сайта XAMPP в файле php.ini ( диск:xamppphpphp.ini ) была по умолчанию отключена библиотека gd:

;extension=gd

Соответственно, все функции imagecreatetruecolor,
imagecreatefromgif,
imagecreatefromjpeg,
imagecreatefrompng и т.д. «вдруг перестали работать».

Решение — убрать точку с запятой из первой позиции указанной выше строки,
сохранить изменённый php.ini, перезагрузиться.

Функция get_magic_quotes_gpc удалена (PHP8)

Любые упоминания о функции get_magic_quotes_gpc теперь придётся исключить из кода, она просто удалена. При этом нужно учесть, что начиная с версии 5.4 она всё равно всегда возвращала 0.

Почему нельзя было оставить в реализации пустое имя функции, а надо заставлять людей переделывать кучу кода — совершенно неясно.

И так у них всё :(

Функция each удалена (PHP8)

Удалена в PHP8 и функция each. В общем случае можно попытаться заменить на next
или array_shift, но однозначного рецепта нет из-за возможности использования функции не только в цикле, как показано выше, но и, например, в рекурсивных построениях.

Фигурные скобки и литералы без кавычек для индексов массива (PHP8)

В PHP8 больше нельзя писать $a{$i} вместо $a[$i] или $foo[bar] вместо $foo['bar']. Просто исправьте это.

Разумеется, если ключ является числовой константой или берётся из переменной, заключать его в апострофы не нужно, $i = 1; $a[$i] или $a[1] — это верный синтаксис.

13.02.2020, 17:35 [18093 просмотра]


Hello all,

I am brand new to Laravel and recently have been following along with a tutorial on learning how to work with it, and in this tutorial we learn how to create a to do list. I am at the very end of this tutorial and at this point we are using livewire to allow us to create new to do step fields in addition to already existing ones when editing a to do. When I go to create a new to do step I get this error:

error-message

I feel the error message gives a pretty clear and obvious statement, but after lots of searching I cannot find a solution.

It tells me line 8 of this edit-step.blade.php is where my error is coming from. Does anyone have any ideas for a solution to this?

code

All help is greatly appreciated

You must be logged in to vote

You are probably trying accessing a non-array type,or It’s a PHP versioning issue please have a look #30737

You must be logged in to vote


6 replies

@austrowGC

If you var_dump $steps and/or $step, what does the output say the type is?

@Muhammad-Sarfaraz

@austinfiddes It happens while you try to get the index ‘arrayIndex’ of an array that does not exist.I think you should try dd() or ddd() and have look on your $steps variable,or you can post it here,it will be helpful, and for further please use @forelse.

@austinfiddes

@austrowGC @Muhammad-Sarfaraz I did try doing a dd on my $steps, I will attach the results below.

Here I did a dd($this->steps)
dd-this-steps

Here I did a dd($steps)
dd-steps

And here is my EditStep controller if this would be helpful to see.
edit-step

@Muhammad-Sarfaraz

@austinfiddes can you please use dd() also in your view,I think your data is not rendered,in your views.

@austinfiddes

@Muhammad-Sarfaraz Here is the result from doing a dd($steps) within the foreach of the view
dd-steps-view

Try Follow these steps, clear your view php artisan view:clear and php artisan cache:clear and remove your html code inside foreach loop and try only echo {{$step[‘name’]}} inside foreach loop,It will helps you to identify which portion of your code is causing this errors.

You must be logged in to vote


0 replies

Bro i have been facing the same problem did you have any solution for it..???

You must be logged in to vote


2 replies

@prudentjag

in your controller when you are fetching the data use $result = DB::table('your table')->where('condition')->get() because I was using $result = DB::table('your table')->where('condition')->first() and it was giving me that error, the in blade you can use forelse to loop it

@workatfolium

i think you misunderstood the problem but i have got solution for my problem thanks for your approach @prudentjag..

I faced the same issue, and after some debugging i understood what make this error happen. So basically is on line 8, you wrote value="{{ $step['name'] }}" your are displaying the name of your step, when you’re getting from database it works fine, but when you want to add new step field, initially it doesn’t have a key called ‘name’ because in your increment method you are just adding a new key with type of int with a value of int also, — see picture bellow to understand more — and that’s what cause this issue. To fix it you just have to change it to value="{{ $step['name'] ?? '' }}"

problem

You must be logged in to vote


1 reply

@workatfolium

Всем привет!
Недавно после обновления системы до версии PHP 7.4 вместе со всеми вытекающими случилась интересная проблема — штука, которая собирала отчёты начала кидаться в меня ошибками в виде Trying to access array offset on value of type int.
Как ни странно, сама проблема кроется именно в библиотеке PHPExcel, которая по неизвестным причинам не обновляется. Решается довольно легко — посредством редактирования файла DefaultValueBinder.php в самой библиотеке. Но забавная история — далеко не все могут просто вот так редактировать библиотеку, например, если она тянется при помощи composer.

Недолго думая сделал форк этой библиотеки. Предоставляю вам два решения проблемы:

С помощью замены пакета в composer.json

Открываем файл composer.json и во-первых добавляем туда репозиторий. Так же, если вдруг вам нужен, добавляем туда и ExcelBundle.

    "repositories": [
        {
            "url": "https://github.com/ruecoder/ExcelBundle.git",
            "type": "git"
        },
        {
            "url": "https://github.com/ruecoder/PHPExcel.git",
            "type": "git"
        }
    ],

Затем закидываем в тот же composer.json в блок require сами библиотеки

    "require": {
        "ruecoder/phpexcel": "dev-master",
        "ruecoder/excelbundle": "dev-master"
    }

И выполняем composer update

С помощью редактирования библиотеки PHPExcel

Всё просто. Идём по пути и открываем файл vendor/PHPExcel/Classes/PHPExcel/Cell/DefaultValueBinder.php
Нам нужна строка 82 которая выглядит вот так:

} elseif ($pValue[0] === '=' && strlen($pValue) > 1) {

заменяем её на такую

} elseif (0 === strpos($pValue, '=') && strlen($pValue) > 1) {

Всё, готово, всё снова работает как и раньше. :)

If you encounter the “Trying to access array offset on value of type int” error while attempting to access a PHP array index, the issue may be that the specified index does not exist in the array.

echo $your_array['key'];

And most likely the array is not null and but the index you are trying to access does not exists.

To avoid this error, verify that the array has the desired index before attempting to access it. One way to accomplish this is by using the following code:

echo isset($your_array['key']) && $your_array['key'];

Alternatively, you can use a ternary operator to check if the index exists and output its value or 0 if it does not:

echo isset($your_array['key']) ? $your_array['key'] : 0;

Software engineer & Blogger has 10+ years of experience working with the Full Stack Web Application Development.

  • Ошибка try slow down or shift up volvo
  • Ошибка u0001 82 range rover evoque
  • Ошибка trx roblox copied error
  • Ошибка u0 на котле daewoo как исправить
  • Ошибка trk0005 не удалось обнаружить cl exe