K
K
Kontrael2020-04-23 11:49:05
PHP
Kontrael, 2020-04-23 11:49:05

Why is a non-existent array key treated as 0 by PHP?

Why as a result of executing the code:

$ar = [ 'TEST'  => "asdf"];

var_dump($ar['TEST']['TEST2']);

Is this the result?
string(1) "a"
Those. apparently the key "TEST2" is interpreted as "0". Shouldn't it be null, according to the documentation?
5ea1563a96502270724915.png
https://www.php.net/manual/ru/language.types.array.php

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Aksentiev, 2020-04-23
@Kontrael

You are looking at the documentation for arrays, but you have an error on accessing the line
https://www.php.net/manual/en/language.types.strin...

F
FanatPHP, 2020-04-23
@FanatPHP

PHP has the functionality to access strings as arrays.
And it displays the existing element of the string-array "asdf" with index 0
to you. It is not null that is brought to zero, which is nowhere to be found, but the string 'TEST2'
PHP at the same time swears with scary words.

V
Vitaly Artemyev, 2020-04-23
@Vitaly48

You are accessing the string as an array

$var = [];
var_dump($var['TEST2']);

NOTICE Undefined index: TEST2 on line number 4
NULL

$var = 'asdf';
var_dump($var['TEST2']);

WARNING Illegal string offset 'TEST2' on line number 8
string(1) "a"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question