packnob890
packnob890

Reputation: 139

Fastest and most efficient way to write if something exists

Here is my code that I want to shorten:

if($array != null) {
    if($array[0] === 1) {
        echo $array[1];
    }
}

here is what im trying to accomplish: execution speed/performance (fastest), and the shortest way to write it.

here is what i tried:

echo ($array[0] === 1 ? $array[1] : null)

but that does not include the if($array != null). how can i do that?

Upvotes: 1

Views: 34

Answers (1)

Jay Blanchard
Jay Blanchard

Reputation: 34406

You could use a ternary statement like this:

echo ($array[0] === 1) ? $array[1] : NULL ;

EDIT: based on update question the OP wants to use a nested ternary (not recommended due to possible maintenance issues). Here is that nest:

(isset($array) && !empty($array)) ? (($array[0] === 1) ? $array[1] : NULL) : NULL 

If the array is not empty, check to see if $array[0] is equal to 1. If it is output $array[1], else output nothing. If the array is empty return NULL.

Upvotes: 1

Related Questions