Reference of PHP
Reference of PHP
Ask Question
What is this?
This is a collection of questions that come up every now and then about syntax in PHP. This is also a
Community Wiki, so everyone is invited to participate in maintaining this list.
Why is this?
It used to be hard to find questions about operators and other syntax tokens.¹
The main idea is to have links to existing questions on Stack Overflow, so it's easier for us to reference
them, not to copy over content from the PHP Manual.
¹ Note: Since January 2013, Stack Overflow does support special characters. Just surround the search
terms by quotes, e.g. [php] "==" vs "==="
If you have been pointed here by someone because you have asked such a question, please find the
particular syntax below. The linked pages to the PHP manual along with the linked questions will likely
answer your question then. If so, you are encouraged to upvote the answer. This list is not meant as a
substitute to the help others provided.
The List
If your particular token is not listed below, you might find it in the List of Parser Tokens.
% Arithmetic Operators
!! Logical Operators
?: Ternary Operator
What is ?: in PHP 5.3?
What are the PHP operators "?" and ":" called and what do they do?
?: operator (the 'Elvis operator') in PHP
Where can I read about conditionals done with "?" and ":" (colon)?
Using PHP 5.3 ?: operator
\ Namespaces
What is the "->" PHP operator called and how do you say it when reading code out loud?
Where do we use the object operator "->" in PHP?
What's the difference between :: (double colon) and -> (arrow) in PHP?
What does the PHP syntax $var1->$var2 mean?
What does "->" mean/refer to in PHP?
=> Arrays
^ Bitwise Operators
= Assignment Operators
== Comparison Operators
How do the PHP equality (== double equals) and identity (=== triple equals) comparison
operators differ?
PHP != and == operators
The 3 different equals
Type-juggling and (strict) greater/lesser-than comparisons in PHP
!= Comparison Operators
| Bitwise Operators
~ Bitwise Operators
Understanding Incrementing
Answer below
.= Assignment Operators
. String Operators
, Variable Declarations
$$ Variable Variables
` Execution Operator
I know this isn't strictly PHP, but what about including a link to phpdoc.org for phpDocumentor
4 Can I suggest square bracket and curly bracket ? – ajreal Nov 26 '11 at 10:38
I ran into this problem a lot too (not being able to search for special characters), which is why I
89 made SymbolHound, a search engine that doesn't ignore special characters. I also posted it on
StackApps. – dncrane Dec 6 '11 at 18:34
A question was asked today (Nov.20/15) stackoverflow.com/questions/33833259/what-is-rscat-
in-php asking "What is $rsCat in php" (should that question still be made visible and not deleted).
3
Strangely enough, there isn't a reference about $ variable, but about $$ Variable Variables only. I
believe that should be amended somewhere. – Fred -ii- Nov 20 '15 at 18:19
Suggestion: move this to the new Stackoverflow documentation. – starbeamrainbowlabs Oct 5 '16
9
at 9:16
show 9 more comments
14 Answers
active oldest votes
Incrementing / Decrementing Operators
++ increment operator
-- decrement operator
If put before the variable, the increment/decrement operation is done to the variable first then the result is
returned. If put after the variable, the variable is first returned, then the increment/decrement operation is done.
For example:
$apples = 10;
for ($i = 0; $i < 10; ++$i) {
echo 'I have ' . $apples-- . " apples. I just ate one.\n";
}
Live example
In the case above ++$i is used, since it is faster. $i++ would have the same results.
Pre-increment is a little bit faster, because it really increments the variable and after that 'returns' the result. Post-
increment creates a special variable, copies there the value of the first variable and only after the first variable is
used, replaces its value with second's.
However, you must use $apples--, since first you want to display the current number of apples, and then you
want to subtract one from it.
You can also increment letters in PHP:
$i = "a";
while ($i < "c") {
echo $i++;
}
Note that character variables can be incremented but not decremented and even so only plain ASCII characters
(a-z and A-Z) are supported.
Understanding Incrementing
The difference is a lot more than just speed... consider $x = 0; $y = $x++; compared with $x = 0; $y = +
1
+$x; and the value of $y in each case – Mark Baker Sep 17 '10 at 16:33
+1 for the note that decrementers don't work on characters, only on numbers – Mark Baker Sep 17 '10 at
5
20:51
For everyone's sake, please remove the bolded information about pre-incrementing being infinitesimally
129 faster. This is the absolute worst example of premature optimization and this kind of information should
not be in people's heads if they are just starting to learn PHP. – Lotus Notes Dec 8 '10 at 23:49
@Lotus - I consider it a fun fact. If you're a beginner to PHP, or C++, etc, it seems pretty wacky that ++i
10 and i++ are different enough to work at different speeds. I found it fascinating. – Peter Ajtai Dec 9 '10 at
10:47
@Peter Ajtai Yes, it's interesting, but from the way you've structured your post you make it seem like
8 one of the prime facts of PHP that is absolutely vital to using the language. – Lotus Notes Dec 9 '10 at
17:43
show 7 more comments
_ Alias for gettext()
add a comment
syntax name description
x == y Equality True if x and y have the same key/value pairs
x != y Inequality True if x is not equal to y
x === y Identity True if x and y have the same key/value pairs in
the same order and of the same types
x !== y Non-identity True if x is not identical to y
++ x Pre-increment Increments x by one, then returns x
x ++ Post-increment Returns x, then increments x by one
-- x Pre-decrement Decrements x by one, then returns x
x -- Post-decrement Returns x, then decrements x by one
x and y And True if both x and y are true x=6 y=3
(x < 10 and y > 1) returns true
x && y And True if both x and y are true x=6 y=3
(x < 10 && y > 1) returns true
a . b Concatenation Concatenate two strings: "Hi" . "Ha"
add a comment
Magic constants: Although these are not just symbols but important part of this token family. There are eight
magical constants that change depending on where they are used.
__FILE__: The full path and filename of the file. If used inside an include, the name of the included file is
returned. Since PHP 4.0.2, __FILE__ always contains an absolute path with symlinks resolved whereas in older
versions it contained relative path under some circumstances.
__DIR__: The directory of the file. If used inside an include, the directory of the included file is returned. This
is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root
directory. (Added in PHP 5.3.0.)
__FUNCTION__: The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name
as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
__CLASS__: The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was
declared (case-sensitive). In PHP 4 its value is always lowercased. The class name includes the namespace it
was declared in (e.g. Foo\Bar). Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait
method, __CLASS__ is the name of the class the trait is used in.
__TRAIT__: The trait name. (Added in PHP 5.4.0) As of PHP 5.4 this constant returns the trait as it was
declared (case-sensitive). The trait name includes the namespace it was declared in (e.g. Foo\Bar).
__METHOD__: The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared
(case-sensitive).
__NAMESPACE__: The name of the current namespace (case-sensitive). This constant is defined in compile-time
(Added in PHP 5.3.0).
Source
community wiki
shareimprove this answer edited Feb 21 '14 at 0:42
2 revs, 2 users 66%
n.1
add a comment
The spaceship operator <=> is the latest comparison operator added in PHP 7. It is a non-associative binary
operator with the same precedence as equality operators (==, !=, ===, !==). This operator allows for simpler
three-way comparison between left-hand and right-hand operands.
e.g.
1 <=> 1; // 0
1 <=> 2; // -1
2 <=> 1; // 1
A good practical application of using this operator would be in comparison type callbacks that are expected to
return a zero, negative, or positive integer based on a three-way comparison between two values. The
comparison function passed to usort is one such example.
Type Operators
instanceof is used to determine whether a PHP variable is an instantiated object of a certain class.
<?php
class mclass { }
class sclass { }
$a = new mclass;
var_dump($a instanceof mclass);
var_dump($a instanceof sclass);
bool(true)
bool(false)
Reason: Above Example $a is a object of the mclass so use only a mclass data not instance of with the
sclass
bool(true)
bool(true)
bool(true)
bool(true)
The above works with 'interfaces' as well. This is useful for checking that a particular interface is
4
available. – Ryan Vincent Feb 24 '14 at 11:38
add a comment
Logical Operators :
$a && $b : TRUE if both $a and $b are TRUE.
$a || $b : TRUE if either $a or $b is TRUE.
$a xor $b : TRUE if either $a or $b is TRUE, but not both.
! $a : TRUE if $a is not TRUE.
$a and $b : TRUE if both $a and $b are TRUE.
$a or $b : TRUE if either $a or $b is TRUE.
Comparison operators :
$a == $b : TRUE if $a is equal to $b after type juggling.
$a === $b : TRUE if $a is equal to $b, and they are of the same type.
$a != $b : TRUE if $a is not equal to $b after type juggling.
$a <> $b : TRUE if $a is not equal to $b after type juggling.
$a !== $b : TRUE if $a is not equal to $b, or they are not of the same type.
$a < $b : TRUE if $a is strictly less than $b.
$a > $b : TRUE if $a is strictly greater than $b.
$a <= $b : TRUE if $a is less than or equal to $b.
$a >= $b : TRUE if $a is greater than or equal to $b.
$a <=> $b : An integer less than, equal to, or greater than zero when $a is respectively less than, equal
to, or greater than $b. Available as of PHP 7.
Arithmetic Operators :
-$a : Opposite of $a.
$a + $b : Sum of $a and $b.
$a - $b : Difference of $a and $b.
$a * $b : Product of $a and $b.
$a / $b : Quotient of $a and $b.
$a % $b : Remainder of $a divided by $b.
$a ** $b : Result of raising $a to the $b'th power (introduced in PHP 5.6)
Incrementing/Decrementing Operators :
++$a : Increments $a by one, then returns $a.
$a++ : Returns $a, then increments $a by one.
--$a : Decrements $a by one, then returns $a.
$a-- : Returns $a, then decrements $a by one.
Bitwise Operators :
$a & $b : Bits that are set in both $a and $b are set.
$a | $b : Bits that are set in either $a or $b are set.
$a ^ $b : Bits that are set in $a or $b but not both are set.
~ $a : Bits that are set in $a are not set, and vice versa.
$a << $b : Shift the bits of $a $b steps to the left (each step means "multiply by two")
$a >> $b : Shift the bits of $a $b steps to the right (each step means "divide by two")
String Operators :
$a . $b : Concatenation of $a and $b.
Array Operators :
$a + $b : Union of $a and $b.
$a == $b : TRUE if $a and $b have the same key/value pairs.
$a === $b : TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
$a != $b : TRUE if $a is not equal to $b.
$a <> $b : TRUE if $a is not equal to $b.
$a !== $b : TRUE if $a is not identical to $b.
Assignment Operators :
$a = $b : The value of $b is assigned to $a
$a += $b : Same as $a = $a + $b
$a -= $b : Same as $a = $a - $b
$a *= $b : Same as $a = $a * $b
$a /= $b : Same as $a = $a / $b
$a %= $b : Same as $a = $a % $b
$a **= $b : Same as $a = $a ** $b
$a .= $b : Same as $a = $a . $b
$a &= $b : Same as $a = $a & $b
$a |= $b : Same as $a = $a | $b
$a ^= $b : Same as $a = $a ^ $b
$a <<= $b : Same as $a = $a << $b
$a >>= $b : Same as $a = $a >> $b
Note
and operator and or operator have lower precedence than assignment operator =.
This means that $a = true and false; is equivalent to ($a = true) and false.
In most cases you will probably want to use && and ||, which behave in way known from languages like C,
Java or JavaScript.
add a comment
Integers, Floats, Strings, Arrays & objects for Three-way comparison of variables.
// Integers
echo 10 <=> 10; // 0
echo 10 <=> 20; // -1
echo 20 <=> 10; // 1
// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1
// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
// Arrays
echo [] <=> []; // 0
echo [1, 2, 3] <=> [1, 2, 3]; // 0
echo [1, 2, 3] <=> []; // 1
echo [1, 2, 3] <=> [1, 2, 1]; // 1
echo [1, 2, 3] <=> [1, 2, 4]; // -1
// Objects
$a = (object) ["a" => "b"];
$b = (object) ["a" => "b"];
echo $a <=> $b; // 0
add a comment
PHP Strings: PHP Strings can be specified in four ways not just two ways:
$str = 'string';
3) Heredoc:
$string = <<<EOD
This is my string
EOD; // print This is my string
$string = <<<'END_OF_STRING'
This is my string
END_OF_STRING; // print This is my string
ANSWER:
=> Is the symbol we humans decided to use to separate "Key" => "Value" pairs in Associative Arrays.
ELABORATING:
To understand this, we have to know what Associative Arrays are. The first thing that comes up when a
conventional programmer thinks of an array (in PHP) would be something similar to:
$myArray3 = [];//option 3
$myArray3[] = 2016;
$myArray3[] = "hello";
$myArray3[] = 33;
Where, if wanted to call the array in some later part of the code, we could do:
So far so good. However, as humans, we might find it hard to remember that index [0] of the array is the value
of the year 2016, index [1] of the array is a greetings, and index [2] of the array is a simple integer value.
The alternative we would then have is to use what is called an Associative Array. An Associative array has a
few differences from a Sequential Array (which is what the previous cases were since they increment the
index used in a predetermined sequence, by incrementing by 1 for each following value).
Durring the declaration of an Associative Array, you don't only include the value of what you want to
put in the array, but you also put the index value (called the key) which you want to use when calling
the array in later parts of the code. The following syntax is used during it's declaration: "key" =>
"value".
When using the Associative Array, the key value would then be placed inside the index of the array to
retrieve the desired value.
For instance:
$myArray1 = array(
"Year" => 2016,
"Greetings" => "hello",
"Integer_value" => 33);//option 1
$myArray2 = [
"Year" => 2016,
"Greetings" => "hello",
"Integer_value" => 33];//option 2
$myArray3 = [];//option 3
$myArray3["Year"] = 2016;
$myArray3["Greetings"] = "hello";
$myArray3["Integer_value"] = 33;
And now, to receive the same output as before, the key value would be used in the arrays index:
FINAL POINT:
So from the above example, it is pretty easy to see that the => symbol is used to express the relationship of an
Associative Array between each of the key and value pairs in an array DURING the initiation of the values
within the array.
Question:
& usually checks bits that are set in both $a and $b are set.
One usefull case of these is easy configurations like give below, so a single integer field can store thousands of
combos for you.
Most people have already read the docs but didn't reliase the real world use case of these bitwise operators.
class Config {
private $config;
if($this->is(Config::TYPE_CAT)){
echo 'cat ';
}
if($this->is(Config::TYPE_DOG)){
echo 'dog ';
}
if($this->is(Config::TYPE_RAT)){
echo 'rat ';
}
if($this->is(Config::TYPE_LION)){
echo 'lion ';
}
if($this->is(Config::TYPE_BIRD)){
echo 'bird ';
}
echo "\n";
}
new Config(Config::TYPE_ALL);
// cat dog rat lion bird
new Config(Config::TYPE_BIRD);
//bird
new Config(Config::TYPE_BIRD | Config::TYPE_DOG);
//dog bird
new Config(Config::TYPE_ALL & ~Config::TYPE_DOG & ~Config::TYPE_CAT);
//rat lion bird
shareimprove this answer edited Mar 20 at 5:37 community wiki