SMG SMG - 22 days ago 6
PHP Question

Creating an empty array in PHP and later checking if it there is some valid elements at an index

In Javascript I would do something like this-

var time_array = [];
if ((previousTime > time_array[i]) || (time_array[i] === undefined) )
{
//Do Something
}


I want to do something similar in PHP

$time_array = array();
if (($previousTime> $time_array[$i]) || ($time_array[$i] === undefined) ))
{
//Do Something

}


I can do this very easily in Javascript , but I am a little confused about it in PHP.

Answer
$time_array = array();
if (!isset($time_array[$i]) || $previousTime > $time_array[$i])
{
    //Do Something

}

It will first check if the variable is set and if it is not, the second condition will never be evaluated, so it's safe to use.

Edit: isset() checks whether a variable is declared and is set to a non-null value. You may want to use: if ($time_array[$i] === null) instead (that would be probably more similar to JS's undefined).