We are upgrading to PHP 8.1. A new feature is that an undefined array key throws a warning.
Unfortunately this interferes with the ability to easily use associative arrays such as $_SESSION variables. I understand the virtues of predefining variables, and am not looking for a discussion on those virtues. The idea of the associative array is that you can add things easily to the session and everything not so assigned is evaluated as null. But now it also throws a warning; something has to be done to deal with that.
Here is an example of some code:
$_SESSION['is_condition'] = true;
In another place in the code, the following occurs
if ($_SESSION['is_condition']) ...
If this occurs in a context where the ‘is_condition’ session variable has not been defined, the desired result of evaluating its value as null is what we want. But now something else has to be done to deal with the possibility that it is undefined.
There are several approaches to dealing with this:
-
Pre-define all session variables having the value of null. Seems like it is not the spirit of associative arrays. Now every script has to invoke a lengthy set of code.
-
Use the null coalesce operator whenever the value of an associative array element is required. This is an ugly requirement to place many, many additional operators throughout the code base.
-
Alter our custom error handling functions to ignore the undefined array key error. A very bad idea to suppress warnings, and adds overhead.
None of these approaches is very desirable.
A theoretical way to solve this would be an array initialization statement that assigns all possible associative keys to null. I don’t know of any such thing.
My question is whether there is some other approach that I am missing, such as a parameter that suppresses this specific warning only.
0 / 0 / 0
Регистрация: 02.12.2019
Сообщений: 32
1
22.01.2022, 01:50. Показов 2006. Ответов 6
Изучаю PHP и на данный момент пытаюсть сделать капчу на картинке. Есть 2 файла, 1 с пользовательской формой, 2 — генерирует картинку. Но при выполнении следующего кода выдает ошибку Undefined array key «random_code» in captchacaptcha.php on line 19. Весь функцыонал работает, но картинки на форме нету, хотя в консоли после этого выдает (я подозреваю это и есть картинка)
PNG
IHDRy+ pHYs+DATxA 0��!c&
z;3&O?4O?4O?4O?4O?4O?4O?4O?4O?4O?4O?4O?4O?4O?4Ouj O4IENDB`
contact.php
| PHP | ||
|
captcha.php
| PHP | ||
|
Помогите пожалуйста.
P.S. скрипт запускает локальный сервер апачи, может там нужно что-то настроить или проверить?
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь
0
- Reproduce the Undefined Index Error
- Use
isset()to Check the Content of$_POST - Use
array_key_exists()to Search the Keys in$_POST - Use
in_arrayto Check if a Value Exists in$_POST - Use Null Coalescing Operator (
??)

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:

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:

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.
- Open the HTML file in your code editor.
- Update the
nameattribute ofFirst nameinput tofirst_nam(we deleted the last “e”). - 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):

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:
See more:
I have 3 checkboxes, which user can check and then submit and I am trying to print out the name of the checkbox, that was checked as first, but i keep getting these 2 errors —
Warning: Undefined array key «fruits» in path on line… (number)
Warning: Trying to access array offset on value of type null in path on line… (number)
Here is the code —
<body> <form action="index.php" method="post"> Apples: <input type="checkbox" name"fruits[]" value="apples"><br> Oranges: <input type="checkbox" name"fruits[]" value="oranges"><br> Pears: <input type="checkbox" name"fruits[]" value="pears"><br> <input type="submit"> </form> <?php $fruits = $_POST["fruits"]; echo $fruits[0]; ?> </body> <pre>
You can see, that there is an if statement, which is commented out. When that if statement is not commented out, then these 2 errors disappear, however the result is still not being printed.
Can anybody please help me?
What I have tried:
a lot of things — especially with the isset part of the php code
You never brought an assignment operator.eg
You wrote name «fruits[]».
Instead of name = «fruits[]».
Hope it helps
Hey make a note of the name attribute in the input element and give it a try.
The below code is for your reference, it is working
<body>
<form action="madLibs.php" method="post">
Apples: <input type="checkbox" name="fruits[]" value = "apples"> <br>
Oranges: <input type="checkbox" name="fruits[]" value = "oranges"> <br>
Pears: <input type="checkbox" name="fruits[]" value = "pears"> <br>
<input type="submit" value="submit">
</form>
<br>
<?php
$fruit = $_POST['fruits'];
echo $fruit[1];
?>
</body>
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900
За последние 24 часа нас посетили 9149 программистов и 786 роботов. Сейчас ищут 398 программистов …
-
roman_php
Активный пользователь- С нами с:
- 20 сен 2009
- Сообщения:
- 29
- Симпатии:
- 0
Доброго времени суток!
Очень прошу показать «на пальцах» ну или как получится, можно просто решением, буду додумывать сам
Из некой формы посредством POST приходит некий многомерный массив, print_r выдает такую структуру массива:
Пытаюсь перебрать каждое значение ключ -> значение
-
foreach ($_POST as $key => $value) {
-
if (gettype($key) === «integer»){
-
echo ‘<strong>№’ . $i++ . ‘</strong></br>’ . «n»;
-
echo ‘Вывод ключа nomer_r_doc: ‘ . $value[‘nomer_r_doc’] . ‘ </br>’ . «n»;
-
echo ‘Вывод ключа vib_r_doc: ‘ . $value[‘vib_r_doc’] . ‘</br>’ . «n»;
-
echo ‘Вывод ключа text_r_doc: ‘ . $value[‘text_r_doc’] . ‘</br>’ . «n»;
-
echo ‘Вывод ключа nomer_r_dog: ‘ . $value[‘nomer_r_dog’] . ‘</br>’ . «n»;
-
echo ‘Вывод ключа vib_r_dog: ‘ . $value[‘vib_r_dog’] . ‘</br>’ . «n»;
-
echo ‘Вывод ключа text_r_dog: ‘ . $value[‘text_r_dog’] . ‘</br>’ . «n»;
-
echo ‘Вывод ключа adres: ‘ . $value[‘adres’] . ‘</br>’ . «n»;
В итоге получаю следующее
№1
Вывод ключа nomer_r_doc: 4.1
Вывод ключа vib_r_doc: risk_doc
Вывод ключа text_r_doc: 1
Вывод ключа nomer_r_dog: 5.1
Вывод ключа vib_r_dog: risk_dog
Вывод ключа text_r_dog: 3Warning: Undefined array key «adres» in F:serverOpenServerdomainsuzresult_uz.php on line 20
Вывод ключа adres:
№2
Вывод ключа nomer_r_doc: 4.2
Вывод ключа vib_r_doc: min_doc
Вывод ключа text_r_doc: 2Warning: Undefined array key «nomer_r_dog» in F:serverOpenServerdomainsuzresult_uz.php on line 17
Вывод ключа nomer_r_dog:Warning: Undefined array key «vib_r_dog» in F:serverOpenServerdomainsuzresult_uz.php on line 18
Вывод ключа vib_r_dog:Warning: Undefined array key «text_r_dog» in F:serverOpenServerdomainsuzresult_uz.php on line 19
Вывод ключа text_r_dog:Warning: Undefined array key «adres» in F:serverOpenServerdomainsuzresult_uz.php on line 20
Вывод ключа adres:Т.е. получается, что первый вложенный массив foreach нормально отрабатывает, а дальше выдает ошибки, Warning: Undefined array key.
Понимаю, что вопрос нубский (я им и являюсь) и в гугле меня не за банили, но вот, что то не нахожу, как перебрать все значения в массиве $_POST. -

Drunkenmunky
Активный пользователь- С нами с:
- 12 авг 2020
- Сообщения:
- 1.323
- Симпатии:
- 257
Это, само по себе, должно было натолкнуть на мысль, что так не делают. Нет?
Извлекайте только то, что ожидаете. Как вариант, можно посчитать общее количество элементов, и если их не столько, сколько должно прийти, то вообще ничего не трогайте.
Например-
if(isset($_POST[‘keyname’]) && my_function($_POST[‘keyname’]) == ‘value’)
-
$var = $_POST[‘keyname’];
-

roman_php
Активный пользователь- С нами с:
- 20 сен 2009
- Сообщения:
- 29
- Симпатии:
- 0
Доброго времени суток. Я понимаю, что вы хотите сказать, что нужно извлекать только нужные значения, но задача именно извлечь все значения.
На другом форуме мне уже подсказали решение и оно работает так как надо:-
foreach ($_POST as $key => $value) {
-
foreach ($value as $key_2 => $value_2) {
-
echo $key_2. ‘=>’.$value_2.»<br />»;
-
else echo $key. ‘=>’.$value.»<br />»;
-

Drunkenmunky
Активный пользователь- С нами с:
- 12 авг 2020
- Сообщения:
- 1.323
- Симпатии:
- 257
Не совсем.
В вашем массиве два уровня. Если их будет больше, то работать оно не будет. -

roman_php
Активный пользователь- С нами с:
- 20 сен 2009
- Сообщения:
- 29
- Симпатии:
- 0
Действительно, согласен с вами, если будет 3 уровня в массиве, уже не сработает. Неужели в php нет возможности отработать массив сколько угодно вложенности друг в друга и при этом если не известно сколько уровней в нем, должно же быть что-то, как то такая задача должна решаться?!
-

- С нами с:
- 1 ноя 2016
- Сообщения:
- 1.522
- Симпатии:
- 345
-

- С нами с:
- 1 дек 2022
- Сообщения:
- 12
- Симпатии:
- 1
Все просто!
Делаем функцию-
function ReadField(&$Src,$Name,$Default=»)
-
return (is_string($Src[$Name])? trim($Src[$Name]) : $Src[$Name]);
-
foreach($Src as $Element)
-
$Value = ReadField($Element,$Name,$Default);
-
if ($Value!==$Default) return $Value;
И наслаждаемся:
-
echo ‘Вывод ключа nomer_r_doc: ‘ . ReadField($_POST,‘nomer_r_doc’,‘undefined’). ‘ </br>’ . «n«;
-
echo ‘Вывод ключа vib_r_doc: ‘ . ReadField($_POST,‘vib_r_doc’,‘undefined’) . ‘</br>’ . «n«;
-
echo ‘Вывод ключа text_r_doc: ‘ . ReadField($_POST,‘text_r_doc’,‘undefined’) . ‘</br>’ . «n«;
-
echo ‘Вывод ключа nomer_r_dog: ‘ . ReadField($_POST,‘nomer_r_dog’,‘undefined’) . ‘</br>’ . «n«;
-
echo ‘Вывод ключа vib_r_dog: ‘ . ReadField($_POST,‘vib_r_dog’,‘undefined’) . ‘</br>’ . «n«;
-
echo ‘Вывод ключа text_r_dog: ‘ . ReadField($_POST,‘text_r_dog’,‘undefined’) . ‘</br>’ . «n«;
-
echo ‘Вывод ключа adres: ‘ . ReadField($_POST,‘adres’,‘undefined’) . ‘</br>’ . «n«;
вывод, будет такой, если взять пример указанный в вопросе
-
Вывод ключа nomer_r_doc: 4.1
-
Вывод ключа vib_r_doc: risk_doc
-
Вывод ключа text_r_doc: 1
-
Вывод ключа nomer_r_dog: 5.1
-
Вывод ключа vib_r_dog: risk_dog
-
Вывод ключа text_r_dog: 3
Содержание
- [Solved] Warning: Undefined array key
- Solution 1: Use isset
- Solution 2: Use Ternary Operator
- Solution 3: Check For Null Value
- Frequently Asked Questions
- Summary
- PHP: Solve undefined key / offset / property warnings. Multi-level nested keys
- Solution 1 – isset function
- Solution 2 – property_exists / array_key_exists functions
- Solution 3 – ?? coalesce operator (>=PHP 7)
- Solution 4 – disable warnings
- Solution 5 – custom function
- Как устранить Undefined array key после назначения переменных через explode()?
- Undefined array key in php _post
- 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
- 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.
- There’s a glaring issue with line 24.
- Then we have lines 69 to 73.
- I have trouble finding the matches for the braces top to bottom.
- Line 49 is commented out so it may try to run the code to post every time.
- 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=’
Источник