Fatal error uncaught error call to undefined function each

Solved! ← php - How can I update code that uses the deprecated each() function?

798 votes

11 answers

Get the solution ↓↓↓

With PHP 7.2,each is deprecated. The documentation says:

Warning This function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

How can I update my code to avoid using it? Here are some examples:

  1. $ar = $o->me;
    reset($ar);
    list($typ, $val) = each($ar);
    
  2. $out = array('me' => array(), 'mytype' => 2, '_php_class' => null);
    $expected = each($out);
    
  3. for(reset($broken);$kv = each($broken);) {...}
    
  4. list(, $this->result) = each($this->cache_data);
    
  5. // iterating to the end of an array or a limit > the length of the array
    $i = 0;
    reset($array);
    while( (list($id, $item) = each($array)) || $i < 30 ) {
        // code
        $i++;
    }
    

When I execute the code on PHP 7.2 I receive the following error:

Deprecated: The each() function is deprecated. This message will be suppressed on further calls

2021-12-19

Write your answer


22

votes

Answer

Solution:

  1. For your first two example cases, you could usekey() andcurrent() to assign the values you need.

    $ar = $o->me;   // reset isn't necessary, since you just created the array
    $typ = key($ar);
    $val = current($ar);
    
  2. $out = array('me' => array(), 'mytype' => 2, '_php_class' => null);
    $expected = [key($out), current($out)];
    

    In those cases, you can usenext() to advance the cursor afterward, but it may not be necessary if the rest of your code doesn’t depend on that.

  3. For the third case, I’d suggest just using aforeach() loop instead and assigning$kv inside the loop.

    foreach ($broken as $k => $v) {
         $kv = [$k, $v];
    }
    
  4. For the fourth case, it looks like the key is disregarded inlist(), so you can assign the current value.

    $this->result = current($this->cache_data);
    

    Like the first two cases, it may be necessary to advance the cursor withnext() depending on how the rest of your code interacts with$this->cache_data.

  5. Fifth can be replaced with afor() loop.

    reset($array);
    for ($i = 0; $i < 30; $i++) {
        $id = key($array);
        $item = current($array);
        // code
        next($array);
    }
    


965

votes


303

votes

Answer

Solution:

I found a way to fix it and thought to share the information. Here are also other cases about how to upgrade each() loops to foreach().

Case 1: Missing $value

reset($array);
while (list($key, ) = each($array)) {

Update to:

foreach(array_keys($array) as $key) {

Case 2: Missing $key

reset($array);
while (list(, $value) = each($array)) {

Update to:

foreach($array as $value) {

Case 3: Not missing anything

reset($array);
while (list($key, $value) = each($array)) {

Update to:

foreach($array as $key => $value) {


800

votes

Answer

Solution:

you could create your owneach() function using key(), current() and next(). then replace your calls with that function, like this:

<?php
function myEach(&$arr) {
    $key = key($arr);
    $result = ($key === null) ? false : [$key, current($arr), 'key' => $key, 'value' => current($arr)];
    next($arr);
    return $result;
}

1.

$ar = $o->me;
reset($ar);
list($typ, $val) = myEach($ar);

2.

$out = array('me' => array(), 'mytype' => 2, '_php_class' => null);
$expected = myEach($out);

3.

for(reset($broken);$kv = myEach($broken);) {...}


265

votes

Answer

Solution:

reset($array);
while (list($key, $value) = each($array)) {

UPDATE

reset($array);
foreach($array as $key => $value) {


704

votes

Answer

Solution:

Here are some ways to do it:

The standardforeach loop (very readable):

foreach($this->contents as list($products_id)) {
    $total_items += $this->get_quantity($products_id);
}

Or, reducing:

$total_items = array_reduce($this->contents, function($acc, $item) {
    return $acc + $this->get_quantity($products_id[0]);
});

Or, in a functional expression:

$total_items = array_sum(array_map([$this, 'get_quantity'],
                         array_column($this->contents, 0)));

None of these methods needreset($this->contents); preceding it.


895

votes

Answer

Solution:

The way you most definitely shouldn’t do is put the function «back into php» by adding it to the auto_prepend_file setting in php.ini

auto_prepend_file = "/var/www/php/auto_prepend.php"

Then make the file and enter in the function with an function_exists wrapper.

<?php
/**
 * Adds the depreciated each() function back into 7.2
 */
if (!function_exists('each')) {
    function each($arr) {
        $key = key($arr);
        $result = ($key === null) ? false : [$key, current($arr), 'key' => $key, 'value' => current($arr)];
        next($arr);
        return $result;
    }
}

This essentially declares the function before your php application runs. When your application tries to run the each function it’ll use your version instead.

This is absolutely not the way you should be approaching this problem, especially in production! However you’re a developer with time constraints and you just want to try arbitrary frameworks for your next project and they haven’t been updated to work on your local development server without winding back your php version.

When you’ve committed to a code base for your project please go ahead and implement the changes in the accepted answer because they do work.

I used Wee Zel’s emulation of the each function


775

votes

Answer

Solution:

To expand on Petro Mäntylä excellent correct answer for Case 3:

Here is a full example of a «Case 3» situation, because I find full examples far more informative that one line code fragments:

This is genuine code from a 3rd party old code base (TCPDF)

DEPRECATED:

while (list($id, $name) = each($attr_array)) {
      $dom[$key]['attribute'][$name] = $attr_array[$id];
      ...              
      ...             
   }

FIXED:

 // while (list($id, $name) = each($attr_array)) {
 foreach($attr_array as $feKey => $feRow){
    // $dom[$key]['attribute'][$name] = $attr_array[$id];
    $dom[$key]['attribute'][$feRow] = $attr_array[$feKey];
    ...
    ...
    }
 unset($feKey,$feRow);


547

votes

Answer

Solution:

Replace this code

while (list($_key,$_resourceTypeNode) = each($GLOBALS['config']['ResourceType'])) {
//             if ($_resourceTypeNode['name'] === $resourceTypeName) {
//                 $this->_resourceTypeConfigCache[$resourceTypeName] = new CKFinder_Connector_Core_ResourceTypeConfig($_resourceTypeNode);

//                 return $this->_resourceTypeConfigCache[$resourceTypeName];
//             }
//         }

with this one

foreach ($GLOBALS['config']['ResourceType'] as $key => $_resourceTypeNode) {
            if (isset($_resourceTypeNode['name'])) {
                if ($_resourceTypeNode['name'] === $resourceTypeName) {
                    $this->_resourceTypeConfigCache[$resourceTypeName] = new CKFinder_Connector_Core_ResourceTypeConfig($_resourceTypeNode);
                    
                    return $this->_resourceTypeConfigCache[$resourceTypeName];
                }
            }
        }


863

votes

Answer

Solution:

 //  while (list($products_id, ) = each($this->contents)) {
   //  $total_items += $this->get_quantity($products_id);
 // }

Update To :

foreach(array_keys($this->contents) as $products_id) {
  $total_items += $this->get_quantity($products_id);
}

Other Condition:

foreach($this->contents as $key =>$value) {
  $total_items += $this->get_quantity($products_id);
}


71

votes

Answer

Solution:

What about using this function?

function array_fetch(array $a) {
   $element = current($a);
   next($a);
   return $element;
}


Share solution ↓

Additional Information:

Date the issue was resolved:

2021-12-19

Link To Source

Link To Answer
People are also looking for solutions of the problem: unable to determine current zabbix database version: the table «dbversion» was not found.

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.


Similar questions

Find the answer in similar questions on our website.

  • #1

Fatal error: Uncaught Error: Call to undefined function each() in /var/www/u22720/data/www/imetator223.myarena.site/sbnasMA/includes/adodb/adodb.inc.php:1154 Stack trace: #0 /var/www/u22720/data/www/imetator223.myarena.site/sbnasMA/install/template/page.5.php(96): ADOConnection->Execute() #1 /var/www/u22720/data/www/imetator223.myarena.site/sbnasMA/install/includes/page-builder.php(64): include(‘/var/www/u22720…’) #2 /var/www/u22720/data/www/imetator223.myarena.site/sbnasMA/install/index.php(33): include_once(‘/var/www/u22720…’) #3 {main} thrown in /var/www/u22720/data/www/imetator223.myarena.site/sbnasMA/includes/adodb/adodb.inc.php on line 1154

Это код ошибки , ошибка на 5 этапе установки МА.
До этого стоял сб обычный. После попытки установки МА , попробовал установить СБ++ , установилось без проблем. Но мне нужен МА.
Что делать ?

  • Команда форума
  • #2

Начать читать системные требования.

  • #3

Начать читать системные требования

Я так понимаю , что косяк в том , что пхп стоит 8.02?
….я с глазами дружу просто)0)
спасибо) сейчас исправлю

  • Команда форума
  • #4

Да, именно в этом.
В PHP 8.0 много того, что юзается зависимостями СБ, пошло под нож.
На 7.4 уже должно нормально работать, но возможны варны и Deprecated сообщения, но против них есть решение в теме.

  • #5

Да, именно в этом.
В PHP 8.0 много того, что юзается зависимостями СБ, пошло под нож.
На 7.4 уже должно нормально работать, но возможны варны и Deprecated сообщения, но против них есть решение в теме.

Fatal error: mysqli error: [1062: Duplicate entry ‘никнейм’ for key ‘user’] in EXECUTE(«INSERT INTO sb_admins(user,authid,password,gid, email, extraflags, immunity) VALUES (‘FederaL’,’мой стим’,’какой то ключ’,-1,’почта’,какие-то цифры)») in /var/www/u22720/data/www/imetator223.myarena.site/sbnasMA/includes/adodb/adodb-errorhandler.inc.php on line 79

всё чудно , теперь другая ошибка

  • Команда форума
  • #6

А это уже потому что у Вас база не пустая.
Очистите её через PMA, потом и раскатывайте. Или просто пересоздайте в ISP Manager, тоже очистит её.

  • #7

А это уже потому что у Вас база не пустая.
Очистите её через PMA, потом и раскатывайте. Или просто пересоздайте в ISP Manager, тоже очистит

Огромное спасибо , сделал всё)

Сообщения автоматически склеены: 28 Апр 2021

А это уже потому что у Вас база не пустая.
Очистите её через PMA, потом и раскатывайте. Или просто пересоздайте в ISP Manager, тоже очистит её.

Так , всё вроде сделал , всё вроде хорошо работает.
Есть текст , которые добавить в админ кастом , что бы управление блокировками стояло вначале , а не в конце?
И ещё. Почему оно добавляет в бд баны и муты , будто их консоль выдает , от имени CONSOLE , а мне нужно , что бы от имени каждого админы было , помочь можешь?

Последнее редактирование: 28 Апр 2021

  • #8

Call to undefined function password_hash() in /var/www/u29793/data/www//install/template/page.5.php on line 85
помогите решить!

Larsalex

Larsalex

♂ скамер, мошенник, жулик, аферюга и ворюга ♂


  • #9

Call to undefined function password_hash() in /var/www/u29793/data/www//install/template/page.5.php on line 85
помогите решить!

Все системные требования соблюдены? Включая версию PHP

stupidstudent

18 / 15 / 0

Регистрация: 25.10.2011

Сообщений: 241

1

29.07.2012, 13:47. Показов 46132. Ответов 6

Метки нет (Все метки)


чем вызвана ошибка?
файл где написана функция, в индексе подключен…

PHP
1
Fatal error: Call to undefined function update_cart() in /index.php on line 52

жалуется при вызове функции:

PHP
1
update_card();

сама функция

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function update_card()
{
    foreach($_SESSION['cart'] as $id => $qty)
    {
        if($_POST[$id] == '0')
        {
            unset($_SESSION['cart'][$id]);
        }
        else
        {
          $_SESSION['cart'][$id] = $_POST[$id];   
        }
    }
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Почетный модератор

Эксперт HTML/CSSЭксперт PHP

16842 / 6720 / 880

Регистрация: 12.06.2012

Сообщений: 19,967

29.07.2012, 13:49

2

значит плохо подключен, либо функцию вызываете еще до того, как подключили сам файл



0



Vovan-VE

13207 / 6595 / 1041

Регистрация: 10.01.2008

Сообщений: 15,069

29.07.2012, 13:58

3

Цитата
Сообщение от stupidstudent
Посмотреть сообщение

Call to undefined function update_cart()

PHP
1
function update_card()

Так корзина или карточка?



1



18 / 15 / 0

Регистрация: 25.10.2011

Сообщений: 241

29.07.2012, 14:07

 [ТС]

4

Цитата
Сообщение от Vovan-VE
Посмотреть сообщение

Так корзина или карточка?

спасибо!
моя не внимательность, наверно, изза бессонной ночи.
Вам на спасибку нажать?, а то 5666 репы, число зверя портить не хочется ))



0



KOPOJI

29.07.2012, 14:15

Не по теме:

Цитата
Сообщение от stupidstudent
Посмотреть сообщение

Вам на спасибку нажать?, а то 5666 репы, число зверя портить не хочется ))

:good:



0



18 / 15 / 0

Регистрация: 25.10.2011

Сообщений: 241

29.07.2012, 14:21

 [ТС]

6

Цитата
Сообщение от Vovan-VE
Посмотреть сообщение

Так корзина или карточка?

не ответил.
корзина.

Не по теме:

ну раз его уже подпортили, я добавлю :)



0



2 / 1 / 1

Регистрация: 03.03.2010

Сообщений: 30

13.12.2015, 10:48

7

проблема бывает в том что я только что мучался два часа с такой же ошибкой.
фишка в том что объявив функцию в классе
я ее вызываю через $method(); а надо вызывать через $this->$method();
$method(); //Ошибка
$this->$method();// Нет ошибки



1



  1. HowTo
  2. PHP Howtos
  3. Call to Undefined Function in PHP

Shraddha Paghdar
Oct 24, 2021
PHP

Call to Undefined Function in PHP

Many of you have encountered this error several times Fatal error: Call to undefined function function_name(). In today’s post, we are finding out how to unravel this error. But before we solve this problem, let’s understand how PHP evaluates the functions.

There are several ways to define functions and call them. Let’s say you write it in the function.php file and call it in the main.php file.

    // function.php
<?php
    namespace fooNamespace {
        function foo() {
            return "Calling foo"
        }
    }
?>
    // main.php
include function.php
<?php
    echo fooNamespacefoo();
?>

Namespaces are qualifiers that enable better management by grouping classes that work together to perform a task. It allows you to use the same name for multiple classes. It is important to know how PHP knows which element of the namespace is required by the code. PHP namespaces work quite a sort of a filesystem. There are 3 ways to access a file in a file system:

  1. Relative file name such as fooBar.txt. It will resolve to fooDirectory/fooBar.txt where fooDirectory is the directory currently busy directory.
  2. Relative path name such as subdirectory/fooBar.txt. It will resolve to fooDirectory/subdirectory/fooBar.txt.
  3. Absolute path name such as /main/fooBar.txt. It will resolve to /main/fooBar.txt.

Namespaced elements in PHP follow an equivalent principle. For example, a class name can be specified in three ways:

  1. Unqualified name/Unprefixed class name:Or,If the current namespace is foonamespace, it will always resolve to foonamespacefoo. If the code is a global, non-namespaced code, this resolves to foo.
  2. Qualified name/Prefixed class name:
    $a = new fooSubnamespacefoo();
    

    Or,

    fooSubnamespacefoo::staticmethod();
    

    If the present namespace is foonamespace, it will always resolve to foonamespacefooSubnamespacefoo. If the code is global, non-namespaced code, this resolves to fooSubnamespacefoo.

  3. Fully qualified name/Prefixed name with global prefix operator:
    $a = new foonamespacefoo();
    

    Or,

    foonamespacefoo::staticmethod();
    

    This always resolves to the literal name laid out in the code, foonamespacefoo.

Now suppose you define a class & call the method of a class within the same namespace.

<?php
    class foo {
        function barFn() {
          echo "Hello foo!"
        }
        function bar() {
            barFn();
            // interpreter is confused which instance's function is called
            $this->barFn();
        }
    }
    $a = new foo();
    $a->bar();
?>

$this pseudo-variable has the methods and properties of the current object. Such a thing is beneficial because it allows you to access all the member variables and methods of the class. Inside the class, it is called $this->functionName(). Outside of the class, it is called $theclass->functionName().

$this is a reference to a PHP object the interpreter created for you, which contains an array of variables. If you call $this inside a normal method in a normal class, $this returns the object to which this method belongs.

Steps to Resolve the Error of Calling to Undefined Function in PHP

  • Verify that the file exists. Find the PHP file in which the function definition is written.
  • Verify that the file has been included using the require (or include) statement for the above file on the page. Check that the path in the require/include is correct.
  • Verify that the file name is spelled correctly in the require statement.
  • Print/echo a word in the included file to ascertain if it has been properly included.
  • Defined a separate function at the end of the file and call it.
  • Check functions are closed properly. (Trace the braces)
  • If you are calling methods of a class, make sure $this-> is written.

Shraddha Paghdar avatar
Shraddha Paghdar avatar

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

LinkedIn

Ezoic

PHP 7 является новой версией языка программирования. Её предшественницей считается PHP 5, т. к. 6 версия так и не была выпущена для общего пользования в связи с возникшими во время разработки проблемами. Но это отдельная тема, а сегодня мы разберем, когда при переводе сайта с PHP 5 на PHP 7 возникает ошибка Fatal error: Uncaught Error: Call to undefined function mysql_connect(), и как её исправить, чтобы наш ресурс заработал быстрее, стабильнее и надежнее.

Ошибка Fatal error

Содержание

  1. С чем связана ошибка Fatal error
  2. Создание резервных копий сайта
  3. Настройка журнала ошибок
  4. Переводим сайт на MySQLi
  5. CP1251 и PHP 7 – как расшифровать непонятный набор символов
  6. Заключение

С чем связана ошибка Fatal error

Ошибка, начинающаяся словами «Fatal error: Uncaught Error:», вызывает прекращение работы скрипта. В нашем случае она вместе с рядом других часто появляется при переводе старого сайта с PHP 5 на PHP 7. Выскакивают либо сообщения с уведомлениями об ошибках, либо просто висит белый экран. Здесь есть 2 пути – либо вернуть все назад, переключившись в панели управления хостингом, либо проявить настойчивость, разобраться с этой ошибкой и работать уже с новой версией PHP. Итак, давайте посмотрим, с чем же конкретно связана наша ошибка.

Текст ошибки Fatal Error

Как видно из самого названия ошибки, проблема связана с тем, что новые версии PHP (начиная с v. 5.5.0) не осуществляют поддержку оригинального расширения MySQL, в связи с чем сайт не собирает и не отправляет данные из БД. В этом случае разработчики предлагают перейти на расширения PDO или MySQLi. Попробуем выполнить несколько простых действий по переходу на MySQLi. Также пользователи иногда сталкиваются с ошибкой Error CertEnroll, возникающей в процессе создания запроса на выпуск сертификата на сайте “Росказна”.

Создание резервных копий сайта

Прежде чем предпринимать какие-либо серьезные попытки исправить Fatal error: Uncaught Error: Call to undefined function mysql_connect, необходимо создать резервные копии своего сайта и БД. Также для того, чтобы была неограниченная возможность экспериментировать, добавляем на хостинге еще один сайт и копируем туда файлы, в которые будем вносить различные корректировки. Подобный подход поможет избежать последствий необдуманных или неосторожных действий с данными – мы их уже не потеряем, т. к. они дополнительно хранятся в резервных копиях. Это актуально при решении различных задач, например, при отладке кода на JavaScript иногда приходится решать ошибку TypeError: Cannot read property ‘xxx’ of undefined.

Настройка журнала ошибок

Также настраиваем ведение журнала ошибок (если этого не было сделано ранее). Открываем файл .htaccess и корректируем информацию в нем. Она должна выглядеть следующим образом.

Настройка журнала ошибок

Мы найдем файл .htaccess, если пройдем путь /home/login/domains/domain.ru/public_html/, где login – это логин нашего аккаунта, а domain.ru – домен нашего сайта. Третья строка на картинке выше показывает, где лежит файл с ошибками PHP, которые записываются в процессе работы сайта. Открыть error.log и просмотреть журнал ошибок возможно при помощи файлового менеджера в Панели управления.

Переводим сайт на MySQLi

Итак, вначале вносим коррективы в конструкцию, при помощи которой сайт подключается к базе данных. Открываем действующую запись.

Команды подключения к БД

  1. Везде mysql меняем на mysqli.
  2. В первой строчке после $password через запятую добавляем $dbname.
  3. Вторую строчку mysql_select_db($dbname, $link) убираем совсем.
  4. В третьей строчке перед ‘set names cp1251’ ставим $link и запятую.

Получается так.

Команды MySQLi

В конструкцию, отвечающую за запросы, также вносим изменения. Берем действующую запись.

Запрос сайта

  1. Также заменяем mysql на mysqli.
  2. Меняем местами то, что заключено в скобки.

Теперь выглядит так.

Коррективы, внесенные в конструкцию, при помощи которой осуществляются запросы

Измененная конструкция, отвечающая за запросы

Открываем следующие популярные функции:

  • mysql_fetch_array();
  • mysql_fetch_row();
  • mysql_fetch_assoc();
  • mysql_fetch_array();
  • mysql_num_rows();
  • mysql_insert_id();
  • mysql_close().

И везде производим замену mysql на mysqli. Наша картина выглядит следующим образом.

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

Теперь сбор и отправка информации из БД должны осуществляться без сбоев.

CP1251 и PHP 7 – как расшифровать непонятный набор символов

Иногда при написании сайта некоторые программисты используют не процедурный подход, являющийся на данный момент самым кратким решением, не раз доказавшим свою эффективность, а кодировку CP1251 и другие. В этом случае при переходе на PHP 7 на экране компьютера вся информация выглядит как непонятный набор палочек и иероглифов. В этом случае пробуем в файле дополнительной конфигурации .htaccess указать кодировку так.

Команда php

Исправляем ситуацию в сайте, написанном при помощи CP1251

Проблемы с компьютером возникают нередко, и многие из них нужно научиться устранять самостоятельно. Например, это такие ситуации, как ошибка html5 Video file not found при просмотре видеороликов в сети или ошибки 0x0001, 0x0003 в дополнительной утилите Nvidia GeForce Experience.

Заключение

В этой статье мы рассмотрели, почему при переводе сайта с PHP 5 на PHP 7 возникает ошибка Fatal error: Uncaught Error: Call to undefined function mysql_connect(), и рассмотрели пути ее решения. Сложного в этом ничего нет, были внесены небольшие коррективы в конструкции, отвечающие за подключение к БД и за запросы. Также коснулись ситуации, когда сайт написан с использованием старой кодировки  CP1251. Надеюсь, что предложенные варианты помогут вам исправить ситуацию и без проблем работать на PHP 7.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Fatal error uncaught error call to a member function setpageproperty
  • Fatal error uncaught error call to a member function fetch on boolean in
  • Fatal error uncaught error array callback has to contain indices 0 and 1
  • Fatal error викед вимс
  • Fatal error арт

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии