0

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.

2 Answers 2

1
$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).

Sign up to request clarification or add additional context in comments.

3 Comments

if you have error_reporting(E_ALL) on, then php will notify you of the undefined index, when using if ($time_array[$i] === null), therefore I would suggest to not do that, and use isset() instead.
That's true, my bad. Thank you for your comment, @Hallur
(!isset($time_array[$i]) || ($time_array[$i] === null) || ($previousTime > $time_array[$i])) - I did something like this and it works for me
0

Just use this: http://www.w3schools.com/php/func_array_key_exists.asp

if (array_key_exists($i,$time_array))
 {
     echo "Key exists!";
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.