2
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$array = [];
$var = 0;

echo $array['foo'];// shows error
echo $var['bar'];//does not show error !

(demo)

This code produces

Notice: Undefined index: foo in /in/WfqtZ on line 10

I'm sorry if this sounds ridicules, but why PHP does not show "Undefined index: bar" in this code ? bar is obviously an undefined index, what makes PHP think that it is defined ?

Accountant م
  • 6,975
  • 3
  • 41
  • 61
  • 1
    [Because it's PHP](https://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/)? – Robert Harvey Jan 02 '19 at 18:05
  • 1
    @RobertHarvey I'm sorry I can't get it. Do you mean this is an expected behavior, however it is bad and should be removed ? – Accountant م Jan 02 '19 at 18:10
  • 1
    Run this first to check if it is an array before indexing it: http://php.net/manual/en/function.is-array.php. Or, y'know, just write your code correctly. – Robert Harvey Jan 02 '19 at 18:13
  • 2
    @RobertHarvey The question is about _why_. If I wrote `$users = []; $user = 0;` and then made a typo in referencing $user instead of $users, like this: `echo $user['foo'];`, I would want to know why I'm not getting a notice message about it. I don't think it's feasible to run a variable through is_array() every time you want to reference it. – RToyo Jan 02 '19 at 18:17
  • I know what the question is about. I stopped worrying about stuff like this a long time ago. As a result, I've managed to maintain at least a portion of my sanity. – Robert Harvey Jan 02 '19 at 18:18

1 Answers1

2

From the documentation:

Array dereferencing a scalar value which is not a string silently yields NULL, i.e. without issuing an error message.

taavs
  • 659
  • 9
  • 15
  • Hm, OK. I thought the OP wanted to know *why,* but I guess not. – Robert Harvey Jan 02 '19 at 19:12
  • He asked about PHP not showing "undefined index" in this situation. The answer covers that. But I could not find any info related to why this is implemented the way it is (really weird imo). – taavs Jan 02 '19 at 19:22
  • I wasn't aware of that line in the documentation before, and if I understand it right, if the official documentation says that, then this is an answer of *why* **because it is an intended behavior made by the the PHP makers.** thank you @RobertHarvey for the comments and thank you taavs for the answer – Accountant م Jan 02 '19 at 19:33