H
H
Hint2011-08-23 11:21:21
PHP
Hint, 2011-08-23 11:21:21

PHP: Do I need to create an array before populating it?

Do I need to initialize an array before adding elements to it?
In the past, I always meticulously checked for the presence of all parent branches of an array, but recently I use only one isset. Now I'm wondering whether it's worth creating parent subarrays or immediately entering the final element (and php will create all intermediate links automatically). How to do it right?
Reading
Was:

echo isset($a['a']) && isset($a['a']['b']) && isset($a['a']['b']['c']) ? 'exists' : 'error';

It became:
echo isset($a['a']['b']['c']) ? 'exists' : 'error';

Record
Was:
if (!isset($_SESSION['voted']) || !is_array($_SESSION['voted']))
{
   $_SESSION['voted'] = array();
}
$_SESSION['voted'][$voteId] = time();

Now: Is it correct to shorten the code in both cases?
$_SESSION['voted'][$voteId] = time();

Answer the question

In order to leave comments, you need to log in

8 answer(s)
B
bruteo, 2011-08-23
@Hint

en2.php.net/manual/en/language.types.array.php
The documentation clearly says that it is possible.
$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type
//If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array

X
xaker1, 2011-08-23
@xaker1

Warnings may appear at the highest level, however, this approach is acceptable.
If $a['a']['b']['c'] exists, then $a['a']['b'] must exist by definition.
So checking parent branches is redundant in this case.

K
kastigar, 2011-08-23
@kastigar

C issetis absolutely correct. But I wouldn't call it "reading" because. issetis a special language construct. If you try to ask the index of a non-array, then:

unset($a);
echo $a['a']['b']['c']; // будет warning
echo $a['a']; // тоже будет warning
isset($a['a']['b']['c']); // не будет warning'а

There are also nuances with the recording. If a variable (even if it is an array element) is not set, then it can be implicitly used as an array. But if it is set and is not an array, then there may be problems:
<?php
unset($a);
$a['a'] = 'a'; // это ок
$a['b'] = 1; // это ок
$a['a'][0] = 'b'; // перезапишет первый символ строки!!!
$a['b'][0] = 'b'; // будет notice, про обращение к скаляру, как к массиву
unset($a);
$a['a']['b']['c']['d'] = 'str'; // тоже ок
$с = new SomeClass;
$с[0] = 'c'; // Если класс имплементил ArrayAccess интерфейс, то вызовется метод offsetGet,
             // иначе Fatal error

So if you are not sure what is contained in a variable or array element, then it is better to explicitly initialize the array.

@
@resurection, 2011-08-24
_

It is impossible to check with isset. for a null value, it returns false. See the doc:
$a = array ('test' => 1, 'hello' => NULL);
var_dump(isset($a['test'])); // TRUE
var_dump(isset($a['hello'])); // FALSE
To check if an array key exists, use array_key_exists():
var_dump(array_key_exists('hello', $a)); // TRUE
en.php.net/manual/en/function.isset.php

W
WebSpider, 2011-08-23
@WebSpider

I think that you need to check if you do not want to overwrite an existing value, i.e.

if (!isset($_SESSION['voted'][$voteId])) {
  // Ещё не голосовали, учитываем голос
  $_SESSION['voted'][$voteId] = time();
}

In other cases, verification is optional. Naturally, if any variables are used inside, they must be checked separately for existence and for the correctness of the type. In this case, you need to make sure that the $voteId variable exists and has a number type

C
charon, 2011-08-23
@charon

I think it's enough to check the end element of the array. And if something confuses you, turn on the PHP error log with the maximum logging level: if there are not even warnings, then everything is ok.

F
Fastto, 2011-08-23
@Fastto

there is the most super-high level - there are no notices, you can use it, version 5.3.6, what will happen next is unknown.

S
Sergey Beresnev, 2011-08-23
@sectus

Maybe refactor the code and replace the array with an object?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question