Ошибка undefined array key php

This error message is meant to help a PHP programmer to spot a typo or a mistake when accessing a variable (or an array element) that doesn’t exist. So a good programmer:

  1. Makes sure that every variable or array key is already defined by the time it’s going to be used. In case a variable is needed to be used inside a function, it must be passed to that function as a parameter.
  2. Pays attention to this error and proceeds to fix it, just like with any other error. It may indicate a spelling error or that some procedure didn’t return the data it should.
  3. Only on a rare occasion, when things are not under the programmer’s control, a code can be added to circumvent this error. But by no means it should be a mindless habit.

Notice / Warning: Undefined variable

Although PHP does not require a variable declaration, it does recommend it in order to avoid some security vulnerabilities or bugs where one would forget to give a value to a variable that will be used later in the script. What PHP does in the case of undeclared variables is issue an error of E_WARNING level.

This warning helps a programmer to spot a misspelled variable name or a similar kind of mistake (like a variable was assigned a value inside of a condition that evaluated to false). Besides, there are other possible issues with uninitialized variables. As it’s stated in the PHP manual,

Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name.

Which means that a variable may get a value from the included file, and this value will be used instead of null that one expects accessing a non-initialized variable, which may lead to unpredictable results. To avoid that, all variables in a PHP file are best to be initialized before use.

Ways to deal with the issue:

  1. Recommended: Declare every variable before use. This way you will see this error only when you actually make a mistake, trying to use a non-existent variable — the very reason this error message exists.

     //Initializing a variable
     $value = ""; //Initialization value; 0 for int, [] for array, etc.
     echo $value; // no error
     echo $vaule; // an error pinpoints a misspelled variable name
    
  • a special case when a variable is defined but is not visible in a function. Functions in PHP have own variable scope, and if you need to use in a function a variable from outside, its value must be passed as a function’s parameter:

    function test($param) {
        return $param + 1; 
    }
    $var = 0;
    echo test($var); // now $var's value is accessible inside through $param
    
  1. Suppress the error with null coalescing operator. But remember that this way PHP won’t be able to notify you about using wrong variable name.

     // Null coalescing operator
     echo $value ?? '';
    

    For the ancient PHP versions (< 7.0) isset() with ternary can be used

     echo isset($value) ? $value : '';
    

    Be aware though, that it’s still essentially an error suppression, though for just one particular error. So it may prevent PHP from helping you by marking an unitialized variable.

  2. Suppress the error with the @ operator. Left here for the historical reasons but seriously, it just shouldn’t happen.

Note: It’s strongly recommended to implement just point 1.

Notice: Undefined index / Undefined offset / Warning: Undefined array key

This notice/warning appears when you (or PHP) try to access an undefined index of an array.

Internal arrays

When dealing with internal arrays, that are defined in your code, the attitude should be exactly the same: just initialize all keys before use. this way this error will do its intended job: notify a programmer about a mistake in their code. So the approach is the same:

Recommended: Declare your array elements:

    //Initializing a variable
    $array['value'] = ""; //Initialization value; 0 for int, [] for array, etc.
    echo $array['value']; // no error
    echo $array['vaule']; // an error indicates a misspelled key

A special case is when some function returns either an array or some other value such as null or false. Then it has to be tested before trying to access the array elements, such as

$row = $stmt->fetch();
if ($row) { // the record was found and can be worked with
    echo $row['name']; 
}

Outside arrays

With outside arrays (such as $_POST / $_GET / $_SESSION or JSON input) the situation is a bit different, because programmer doesn’t have the control over such arrays’ contents. So checking for some key existence or even assigning a default value for a missing key could be justified.

  • when a PHP script contains an HTML form, it is natural that on the first load there is no form contents. Therefore such a script should check if a form was submitted

      // for POST forms check the request method
      if ($_SERVER['REQUEST_METHOD'] === 'POST') {
          // process the form
      }
      // for GET forms / links check the important field
      if (isset($_GET['search'])) {
          // process the form
      }
    
  • some HTML form elements, such as checkboxes, aren’t sent to the server if not checked. In this case it is justified to use a null coalescing operator to assign a default value

      $agreed = $_POST['terms'] ?? false;
    
  • optional QUERY STRING elements or cookies should be treated the same way

      $limit = $_GET['limit'] ?? 20;
      $theme = $_COOKIE['theme'] ?? 'light';
    

But assignments should be done at the very beginning of the script. Validate all input, assign it to local variables, and use them all the way in the code. So every variable you’re going to access would deliberately exist.

Related:

  • Notice: Undefined variable
  • Notice: Undefined Index
  1. Reproduce the Undefined Index Error
  2. Use isset() to Check the Content of $_POST
  3. Use array_key_exists() to Search the Keys in $_POST
  4. Use in_array to Check if a Value Exists in $_POST
  5. Use Null Coalescing Operator (??)

Undefined Index With PHP Post

This article teaches four solutions to undefined index in PHP $_POST. The solutions will use isset(), array_key_exists(), in_array(), and the Null coalescing operator.

First, we’ll reproduce the error before explaining the solutions. Meanwhile, in PHP 8, undefined index is the same as undefined array key.

Reproduce the Undefined Index Error

To reproduce the error, download XAMPP or WAMP and create a working directory in htdocs. Save the following HTML form in your working directory as sample-html-form.html.

The form has two input fields that accept a user’s first and last names. You’ll also note that we’ve set the form’s action attribute to 0-reproduce-the-error.php.

Code — sample-html-form.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Sample HTML Form</title>
    <style type="text/css">
        body { height: 100vh; display: grid; place-items: center; }
        main { display: grid; outline: 3px solid #1a1a1a; width: 50%; padding: 0.5em; }
        form { align-self: center; justify-self: center; width: 50%;}
        input:not([type="submit"]) { width: 50%; }
        input[type="submit"] { padding: 0.5em;}
        .form-row { display: flex; justify-content: space-between; margin-bottom: 1rem; }
        .form-row:last-child { justify-content: center; }
    </style>
</head>
<body>
    <main>
        <!--
            This is a sample form that demonstrates how
            to fix the undefined index in post when using
            PHP. You can replace the value of the "action"
            attribute with any of the PHP code in
            this article.

            - DelftStack.com
        -->
        <form method="post" action="0-reproduce-the-error.php">
            <div class="form-row">
                <label id="first_name">First name</label>
                <input name="first_name" type="text" required>
            </div>
            <div class="form-row">
                <label id="last_name">Last name</label>
                <input type="text" name="last_name" required>
            </div>
            <div class="form-row">
                <input type="submit" name="submit_bio_data" value="Submit">
            </div>
        </form>
    </main>
</body>
</html>

Code — 0-reproduce-the-error.php:

<?php
    // The purpose of this script is to reproduce
    // the undefined index or undefined array
    // key error messages. Also, it requires
    // that the $_POST array does not contain
    // the first_name and last_name indexes.
    // DO NOT USE THIS CODE ON PRODUCTION SERVERS.
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];

    if ($first_name && $last_name) {
        echo "Your first name is " . htmlspecialchars($first_name);
        echo "Your last name is " . htmlspecialchars($last_name);
    }
?>

Now, open the HTML form in your web browser. Then type empty strings into the input fields and hit the submit button.

In PHP 5, you’ll get an output like the one shown in the following image. The image shows that undefined index is a Notice in PHP 5.

Output:

Undefined index in PHP 5

If you use PHP 8, undefined index becomes undefined array key. Also, unlike PHP 5, undefined array key is a Warning in PHP 8.

Output:

Undefined array key in PHP 8

The next thing is to show you different ways that will solve it.

Use isset() to Check the Content of $_POST

With isset(), you can check $_POST before using any of its contents. First, set up an if...else statement that uses isset() in its conditional check.

The code in the if block should only execute if isset() returns true. By doing this, you’ll prevent the undefined index error.

In the code below, we are checking if the name attributes of the HTML form exist in $_POST. Also, we ensure the user has not entered empty strings.

If the check returns true, we print the user-supplied data. Save the PHP code as 1-fix-with-isset.php in your working directory and link it with the HTML form.

Code — 1-fix-with-isset.php:

<?php
    // It's customary to check that the user clicked
    // the submit button.
    if (isset($_POST['submit_bio_data']) && !empty($_POST)) {
        // In the following "if" statement, we check for
        // the following:
        // 1. The existence of the first_name last_name
        // in $_POST.
        // 2. Prevent the user from supplying an empty
        // string.
        if (isset($_POST['first_name'], $_POST['last_name'])
            && !empty(trim($_POST['first_name']))
            && !empty(trim($_POST['last_name'])))
        {
            echo "Your first name is " . htmlspecialchars($_POST['first_name']);
            echo "Your last name is " . htmlspecialchars($_POST['last_name']);
        } else {
            // If the user sees the following message, that
            // means either first_name or last_name is not
            // in the $_POST array.
            echo "Please fill all the form fields";
        }
    } else {
        echo "An unexpected error occurred. Please, try again.";
    }
?>

Output (when the user supplies empty values):

Use array_key_exists() to Search the Keys in $_POST

The array_key_exists() as its name implies will search for a key in $_POST. In our case, these keys are the name attributes of the HTML form inputs.

We’ll only process the form if array_key_exists() find the name attributes in $_POST. To be safe, we use the empty() function to ensure the user entered some data.

You’ll find all these in the following code. To test the code, save it as 2-fix-with-array-key-exists.php in your working directory, and link it with your HTML form by updating the value of the action attribute.

Now, do the following steps.

  1. Open the HTML file in your code editor.
  2. Update the name attribute of First name input to first_nam (we deleted the last “e”).
  3. Switch to your Web browser and fill out the first and last names.

An error will occur when you fill the form with the correct data. That’s because there is a mismatch between first_nam and first_name.

The PHP script expected the latter, but it got the former. Without the error checking, you’ll get the undefined index or undefined array key.

Code — 2-fix-with-array-key-exists.php:

<?php
    // Ensure the user clicked the submit button.
    if (isset($_POST['submit_bio_data']) && !empty($_POST)) {
        // Use array_key_exists to check for the
        // first_name and last_name fields. At the
        // same time, prevent the user from supplying
        // an empty string. You can also implement other
        // validation checks depending on your use case.
        if (array_key_exists('first_name', $_POST) && array_key_exists('last_name', $_POST)
            && !empty(trim($_POST['first_name']))
            && !empty(trim($_POST['last_name']))
        )
        {
            echo "Your first name is " . htmlspecialchars($_POST['first_name']) . "<br />";
            echo "Your last name is " . htmlspecialchars($_POST['last_name']);
        } else {
            echo "Please fill all the form fields";
        }
    } else {
        echo "An unexpected error occurred. Please, try again.";
    }
?>

Output (pay attention to the highlighted part in DevTools):

Filling an HTML form that has incorrect name attributes

Use in_array to Check if a Value Exists in $_POST

PHP in_array() function can search $_POST for a specific value. Knowing this, we can use it to confirm if the user filled the HTML form.

Together with the empty() function, we can ensure the user did not supply empty strings. Both the searching and emptiness check prevents undefined index or undefined array key.

In the example detailed below, we use in_array and empty() to prevent the undefined index error. Save the PHP code as 3-fix-with-in-array.php, then set the action attribute of the HTML with the name of the PHP file.

Open the HTML form, fill the Last name field, and leave the First name blank. Submit the form, and you’ll get the custom error message because in_array did not find the first name in $_POST.

Code — 3-fix-with-in-array.php:

<?php
    // Ensure the user clicked the submit button.
    if (isset($_POST['submit_bio_data']) && !empty($_POST)) {
        // Use in_array to check for the first and last
        // name fields. Also, check for empty submissions
        // by the user. We advise that you implement other
        // checks to suit your use case.
        if (in_array('first_name', $_POST) && in_array('last_name', $_POST)
            && !empty(trim($_POST['first_name']))
            && !empty(trim($_POST['last_name']))
        )
        {
            echo "Your first name is " . htmlspecialchars($_POST['first_name']) . "<br />";
            echo "Your last name is " . htmlspecialchars($_POST['last_name']);
        } else {
            echo "Please fill all the form fields";
        }
    } else {
        echo "An unexpected error occurred. Please, try again.";
    }
?>

Output:

Use Null Coalescing Operator (??)

The null coalescing operator (??) will return the operand on its left side if it exists. Otherwise, it’ll return the operand on the right.

Armed with this knowledge, we can pass an input value to the Null coalescing operator. As a result, if the value exists, the operator will return it; otherwise, we’ll make it return another value.

In the code below, we’ll check if the Null coalescing operator returned this other value. If it does, that means one of the form inputs is not in $_POST.

With this, we can show a custom error message other than undefined index or undefined array key. Save the code as 4-fix-with-null-coalescing-operator.php and link it with your HTML form.

Then, open your web browser and fill out the form with the correct data. You’ll get no error messages when you submit the form.

Code — 4-fix-with-null-coalescing-operator.php:

<?php
    // It's customary to check that the user clicked
    // the submit button.
    if (isset($_POST['submit_bio_data']) && !empty($_POST)) {
        // This works in PHP 7 and above. It's called
        // the null coalescing operator. It'll return
        // the value on the left if it exists or the
        // value on the right if it does not. While
        // By doing this, we ensure the user does not
        // enter empty strings. What's more, you can
        // implement other checks for your use case.
        $first_name = !empty(trim($_POST['first_name'])) ?? 'Missing';
        $last_name = !empty(trim($_POST['last_name'])) ?? 'Missing';
        // if the null coalescing operator returns
        // the string "Missing" for first_name
        // or last_name, that means they are not valid
        // indexes of the $_POST array.
        if ($first_name && $last_name !== 'Missing') {
            echo "Your first name is " . htmlspecialchars($_POST['first_name']) . "<br />";
            echo "Your last name is " . htmlspecialchars($_POST['last_name']);
        } else {
            // If the user sees the following message, that
            // means either first_name or last_name is not
            // in the $_POST array.
            echo "Please fill all the form fields";
        }
    } else {
        echo "An unexpected error occurred. Please, try again.";
    }
?>

Output:

Содержание

  1. [Solved] Warning: Undefined array key
  2. Solution 1: Use isset
  3. Solution 2: Use Ternary Operator
  4. Solution 3: Check For Null Value
  5. Frequently Asked Questions
  6. Summary
  7. PHP: Solve undefined key / offset / property warnings. Multi-level nested keys
  8. Solution 1 – isset function
  9. Solution 2 – property_exists / array_key_exists functions
  10. Solution 3 – ?? coalesce operator (>=PHP 7)
  11. Solution 4 – disable warnings
  12. Solution 5 – custom function
  13. Как устранить Undefined array key после назначения переменных через explode()?
  14. Undefined array key in php _post
  15. All 8 Replies

[Solved] Warning: Undefined array key

To solve Warning: Undefined array key in PHP You just need to check that what you are trying to get value exists or Not So you have to use isset. Just like this. Now, Your error must be solved. Let’s explore the solution in detail.

Solution 1: Use isset

You just need to check that what you are trying to get value exists or Not So you have to use isset. Just like this. Now, Your error must be solved.

Solution 2: Use Ternary Operator

You can also Use Ternary Operator as a Conditional Statement. Ternary Operator syntax is (Condition) ? (Statement1) : (Statement2); We can use Just Like this.

And now Your error must be solved.

Solution 3: Check For Null Value

Usually, This error occurs Cause Of a Null Or Empty Value So You need to use a Conditional Statement here. You can achieve this Just like the given below.

We can Also Use Multiple Conditions Cause the Value should be Null Or Empty So We are Going to use both Conditions in our IF.

And now, Your error will be solved.

Frequently Asked Questions

  1. How To Solve Warning: Undefined array key Error ?

To Solve Warning: Undefined array key Error You can also Use Ternary Operator as a Conditional Statement. Ternary Operator syntax is (Condition) ? (Statement1) : (Statement2); And now Your error must be solved.
Warning: Undefined array key

To Solve Warning: Undefined array key Error You Just need to check that what you are trying to get value is exists or Not So you have to use isset. Just like this. Now, Your error must be solved.

Summary

The solution is quite simple you need to check for null or empty values before using any variable. You can use isset(), if-else or ternary operator to check null or empty values. Hope this article helps you to solve your issue. Thanks.

Источник

PHP: Solve undefined key / offset / property warnings. Multi-level nested keys

Sometimes we may want to return null or empty string for non-existing multi-level/nested keys or properties in PHP instead of warnings. Also it would be convenient to use bracket ([]) and arrow (->) operators for array keys / object properties interchangeably.

First let’s initialize some variables in below PHP code block:

Now let’s execute the following:

The output of the above code will be (no errors or warnings, all clean):

The output will be:

Solution 1 – isset function

We can use PHP’s isset($var) function to check if variable is set before using it. This will solve undefined key and undefined property issues.

This solution fixes only undefined key/property issue, but Cannot use object of type Foo as array error still remains. Also we need to call the same key twice which may be problematic for very large arrays.

Solution 2 – property_exists / array_key_exists functions

Similar to Solution1 we can use PHP’s property_exists($cls, $prop) and array_key_exists($key, $arr) functions that would fix undefined key/property issue perfectly:

The output will be similar to Solution1. But syntactically speaking this is not the best solution.

Solution 3 – ?? coalesce operator (>=PHP 7)

Output is the same and Cannot use object of type Foo as array error still remains. But this solution seems better than others.

Solution 4 – disable warnings

Solution 5 – custom function

Finally, we can develop our own custom function, that will solve all of the problems. It is also possible to mix array keys and object properties in key chain list.

God, His angels and all those in Heavens and on Earth, even ants in their hills and fish in the water, call down blessings on those who instruct others in beneficial knowledge.

Источник

Как устранить Undefined array key после назначения переменных через explode()?

Хочу перевести скрипты с php 5.2 на 8 но столкнулся с постоянными ошибками о неназначенных переменных. И если большинство сразу налету можно вписать в условие isset(), перед назначением, когда она назначается в цикле for например.
Ну или когда передается методом POST, GET или штучно назначается.

Но как быть с explode? У меня их очень много и переделывать их все на циклы нет возможности.

Вот такой вот код выдает ошибку в заголовке этой темы:

Как быть? Как менее болезненно устранить все эти Undefined array key в коде, везде, где есть explode()

Это ладно когда еще небольшая входящая может быть. Но у меня есть проверки файлов в которых допустим 60 ячеек с которых берутся данные. Где-то ячейки пустые, где-то с данными. Не писать же для каждой отдельно проверку.

  • Вопрос задан 22 окт. 2022
  • 426 просмотров

На «западном аналогичном этому сайте» только что случайно наткнулся на красивое решение.

где 666 — это количество колонок, которое должно быть после explode.
array_pad добьёт их пустыми строками. можно поставить нули при желании.

Это если $file[0] окажется пустым, то $arrdata все ключи заполнит либо », либо нулями, если их указать?
Или это добавляет к имеющемуся массиву эти значения?
Прочел об array_pad, но так и не понял, в конкретном случае, что оно сделает.

Ну и сразу вопрос, чем результат будет отличаться от $data=explode(«|», $file[0] ?? »); ?

Ипатьев, Я этот метод запомнил, думаю обязательно еще пригодится, но все же принял волевое решение не пытаться обмануть PHP. Сел, запасся терпением и поехал построчно по всем пунктам, вооружившись isset() и empty(). Иначе это бесконечно будет продолжаться, одно подавляешь, другое всплывает. Лучше уж привести код к положенным стандартам, а не искать костыли.

Прошел все стадии, пришла стадия принятия)

isset и empty — это не «положенные стандарты», а как раз наоборот — костыли. И я об этом в каком-то из комментариев уже писал.

Но главное — это сразу становится понятным, если немного подумать головой.
Эти ошибки, Undefined array key — они не для того, чтобы программист задолбался.
А вы их воспринимаете именно так. Вы считаете, что создатели языка заставляют вас везде писать isset и empty. Но это же глупость — писать код только для того, чтобы задавить сообщение об ошибке!

Задача этих ошибок не в том, чтобы программист все время как обезьяна везде писал isset и empty.
Любые сообщения об ошибках — служат для помощи программисту.
Данная ошибка подсказывает, что программист пытается обратиться к переменной, или элементу массива которых нет.
И увидев эту ошибку, программист не должен тупо затыкать ей рот через isset! А должен разобраться — почему вдруг нет нужной переменной.

То есть «положенные стандарты» — это чтобы переменная всегда была на месте.
Мало того что это сильно упрощает код — без всех этих isset и empty — но главное, эти ошибки начнут реально приносить пользу, когда программист реально ошибется в имени переменной или попытается обратиться к несуществующему элементу массива.

А то что вы делаете сейчас — это то же самое подавление ошибок, вид сбоку.

Все что я написал — нетрудно понять просто логикой. Но если вам обязательно нужно, то вот вам статья с англоязычного ресурса, https://phpdelusions.net/articles/null_coalescing_abuse

Причем array_pad — это тоже костыль. И по идее, надо приводить свои файлы в порядок, чтобы в них не было пустых ячеек. Но на данном этапе использование array_pad оправдано, поскольку приводит все массивы к единому виду. То есть делает то, что вы хотели изначально — чтобы if($arrdata[19]>0)< не вызывало ошибок. Потому что в $arrdata всегда будет нужное число колонок.

Задача этих ошибок не в том, чтобы программист все время как обезьяна везде писал isset и empty.
Любые сообщения об ошибках — служат для помощи программисту.
Данная ошибка подсказывает, что программист пытается обратиться к переменной, или элементу массива которых нет.
И увидев эту ошибку, программист не должен тупо затыкать ей рот через isset! А должен разобраться — почему вдруг нет нужной переменной.

На словах все очень хорошо звучит. А то я этого не понимаю.

А теперь ситуация, которых может быть уйма.

На сайте может создаваться файл, может не создаваться, он может быть с данными, а может быть пустой, в зависимости от действий пользователя.

Мы через explode считываем данные этого файла назначая переменные, через ключи, что назначаются в explode.

И какие варианты? Мы проверяем либо что файл не пустой, либо мы потом проверяем есть ли переменная назначенная или нет.

В любом случае мы делаем эту проверку. И таких моментов сотня может быть, так как весь сайт использует сплошные файлы. Так понятней объяснил? А то красиво, конечно, говорить, не зная сути дела, как на самом деле обстоит обстановка. Если есть решение как в таких ситуациях поступать дабы избежать isset или empty, я с радостью выслушаю. По поводу file_exists писать не стоит, файлы всегда в наличии, ну в большинстве случаев, а вот внутренности могут пустыми. Причем внутренности разделены на строки и разделены на столбцы. Данные перемешиваются, это могут быть как string так и int что тоже надо постоянно проверять.

Ипатьев, файлы не пустые и так. Ячейка может быть пустой в зависимости от того, какое действие сделал пользователь. Например, в нее занеслось Apple, а если он не сделал какое-то действие, то будет «». Вы же не предлагаете в КАЖДОЙ ячейке по умолчанию вписывать default, только для того что бы она была не пустой. Тем более некоторые ячейки создаются в процессе, могут дополняться путем пуша или .=

Источник

Undefined array key in php _post

Hi everyone here,
I’m trying to show information about the material according to the year of meeting(is a meeting when they decide to buy a new material)
so I use a drop-down list and the information will show according to the year chosen by the user, but it shows the error as is mentioned in the title.
this the code.
Thanks in advance.

    3 Contributors 8 Replies 6K Views 8 Hours Discussion Span Latest Post 1 Year Ago Latest Post by Dani

I think what rproffitt is referring to is the space between the array’s variable name and the array index. It should be $row[‘annee’] with no space between the $row and the [ .

Undefined array key in php _post

You mention the error message is in the topic title, but typically PHP errors specify the line that the error is occurring on.

Formatting could help.

  1. There’s a glaring issue with line 24.
  2. Then we have lines 69 to 73.
  3. I have trouble finding the matches for the braces top to bottom.
  4. Line 49 is commented out so it may try to run the code to post every time.
  5. Line 49’s bracket, since the line is commented out may have a stray bracket below.

The formatting is a mess so I’ll stop here.

idk why u have found my code in a mess, for line 24 there are two braces one for the if statement and the second for the while statement, Unlike you I see that every brace is in the place he must be
thanks for ur reply

To me, this is poorly formatted so that stood out fast. Example at ‘ data-bs-template=’

I know some don’t think it matters and some get upset about it. In school, such would be kicked back with either «try again», rejected or reduced grade. Here you are asking for help so put in the effort to present clean readable code.

Also, why is line 49 commented out?

PS. Dump variables before the line it fails at to check your work. Nod to ‘ data-bs-template=’

Источник

Всем привет!

Хочу перевести скрипты с php 5.2 на 8 но столкнулся с постоянными ошибками о неназначенных переменных. И если большинство сразу налету можно вписать в условие isset(), перед назначением, когда она назначается в цикле for например.
Ну или когда передается методом POST, GET или штучно назначается.

Но как быть с explode? У меня их очень много и переделывать их все на циклы нет возможности.

Вот такой вот код выдает ошибку в заголовке этой темы:

$pr_ip = explode(".", $ip_addr);
$my_ip = $pr_ip[0].$pr_ip[1].$pr_ip[2];

Как быть? Как менее болезненно устранить все эти Undefined array key в коде, везде, где есть explode()

Это ладно когда еще небольшая входящая может быть. Но у меня есть проверки файлов в которых допустим 60 ячеек с которых берутся данные. Где-то ячейки пустые, где-то с данными. Не писать же для каждой отдельно проверку.

Are you having problems with the issue “Warning: Undefined array key“? How to fix it? In today’s article, I will provide solutions for you to solve the issues. Please follow the below steps to get the problem resolved now

How did “Warning: Undefined array key” occur?

Warning: Undefined array key

When you work with PHP, you may get the issue Warning: Undefined array key. Don’t worry, we are here to provide you solutions in order to resolve your problem.

How to fix “Warning: Undefined array key”?

To Solve Warning : Undefined array key error, you just need to verify that the value you want to obtain is actually there. Simply pke this. Now, you must correct your error.

Solution 1: Use the isset

It is enough to verify that the value you seek is there. As simple as that. This is how to fix your error.

<?php if(isset($_GET['name'])): ?>
        Your name is <?php echo $_GET["name"]; ?>
<?php endif; ?>

Final words

The above are useful solutions that can help you fix “Warning: Undefined array key” problem, if you can’t solve it well. Please leave a message.

I have the following code:

<form action="calculator.php" method="get">
  <label for="age">Enter your age</label>
  <input type="number" id="age" name="age">

  <br>
  <label for="height">Enter your height</label>
  <input type="number" id="height" name="height">
  <br>

  <input type="submit">
</form>

<?php
$age = $_GET["age"];
$height = $_GET["height"];

if (isset($age) && isset($height)) {
  echo ($age + $height);
}
?>

This gives me the warnings: Warning: Undefined array key «age» in (file location) and Undefined array key «height» in (file location).

As you can see I’m not using arrays. I googled this and tried putting the echo statement inside an if ( isset() ), but it still gives me the same warning.

Can someone tell me why and how to fix this?

Biswajit Biswas's user avatar

asked Jun 14, 2021 at 9:51

Michael Tran's user avatar

7

$_GET is an empty array on this case that’s why they are undefined keys.
You should check if $_GET has age and height.
You can do something like this:

if(isset($_GET['age'], $_GET['height'])){
    // do the calculation 
}

answered Jun 14, 2021 at 10:06

Gazmend Sahiti's user avatar

Try using extract function.

<?php
extract($_GET);
/*$age = $_GET["age"];
$height = $_GET["height"];
*/
if (isset($age) && isset($height)) {
  echo ($age + $height);
}
?>

answered Jun 16, 2021 at 8:21

XMehdi01's user avatar

XMehdi01XMehdi01

4,7262 gold badges8 silver badges25 bronze badges

  • Ошибка unexpected store extension
  • Ошибка unb на стиральной машине леран
  • Ошибка unb на стиральной машине hisense
  • Ошибка unb на стиральной машине haier что это такое
  • Ошибка unb на стиральной машине haier что делать