Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP "or" Syntax

I've seen this a lot: $fp = fopen($filepath, "w") or die(); But I can't seem to find any real documentation on this "or" syntax. It's obvious enough what it does, but can I use it anywhere? And must it be followed by die()? Are there any caveats to using or when you could use something like

if (file_exists($filepath))    $fp = fopen($filepath,"r"); else    myErrMessage(); 

I know it seems like a silly question, but I can't find any hard and fast rules for this. Thanks.

like image 900
Andrew Avatar asked Mar 02 '12 14:03

Andrew


People also ask

What does || mean in programming?

Logical OR operator: || The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise. The operands are implicitly converted to type bool before evaluation, and the result is of type bool . Logical OR has left-to-right associativity.

What does this -> mean in PHP?

The object operator, -> , is used in object scope to access methods and properties of an object. It's meaning is to say that what is on the right of the operator is a member of the object instantiated into the variable on the left side of the operator.

What is the use of $$ and operator in PHP?

Use the PHP AND operator ( and , && ) to combine two boolean expressions and returns true if both expressions evaluate to true; otherwise, it returns false . The logical AND operator is short-circuiting.

What does === mean in PHP?

=== It is equal to operator. It is an identical operator. It is used to check the equality of two operands. It is used to check the equality of both operands and their data type.


2 Answers

It's a logical operator and can be used in any logical expression.

http://php.net/manual/en/language.operators.logical.php

like image 107
Smamatti Avatar answered Sep 24 '22 22:09

Smamatti


Let's just say that:

$result = first() || second(); 

will evaluate to:

if (first()) {     $result = true; } elseif (second()) {     $result = true; } else {     $result = false; }  

while:

$result = first() or second(); 

will evaluate to:

if ($result = first()) {     // nothing } else {     second(); } 

In other words you may consider:

$result = first() || second();  $result = (first() || second()); 

and:

$result = first() or second(); 

to be:

($result = first()) || second(); 

It is just matter of precedence.

like image 39
tacone Avatar answered Sep 25 '22 22:09

tacone