What is <=> (the 'Spaceship' Operator) in PHP 7? [duplicate] - php

This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 7 years ago.
The community reviewed whether to reopen this question last month and left it closed:
Original close reason(s) were not resolved
PHP 7 introduced the Spaceship (<=>) operator. What is it and how does it work?

The <=> ("Spaceship") operator will offer combined comparison in that it will :
Return 0 if values on either side are equal
Return 1 if the value on the left is greater
Return -1 if the value on the right is greater
The rules used by the combined comparison operator are the same as the currently used comparison operators by PHP viz. <, <=, ==, >= and >. Those who are from Perl or Ruby programming background may already be familiar with this new operator proposed for PHP7.
//Comparing Integers
echo 1 <=> 1; //output 0
echo 3 <=> 4; //output -1
echo 4 <=> 3; //output 1
//String Comparison
echo "x" <=> "x"; //output 0
echo "x" <=> "y"; //output -1
echo "y" <=> "x"; //output 1

According to the RFC that introduced the operator, $a <=> $b evaluates to:
0 if $a == $b
-1 if $a < $b
1 if $a > $b
which seems to be the case in practice in every scenario I've tried, although strictly the official docs only offer the slightly weaker guarantee that $a <=> $b will return
an integer less than, equal to, or greater than zero when $a is respectively less than, equal to, or greater than $b
Regardless, why would you want such an operator? Again, the RFC addresses this - it's pretty much entirely to make it more convenient to write comparison functions for usort (and the similar uasort and uksort).
usort takes an array to sort as its first argument, and a user-defined comparison function as its second argument. It uses that comparison function to determine which of a pair of elements from the array is greater. The comparison function needs to return:
an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
The spaceship operator makes this succinct and convenient:
$things = [
[
'foo' => 5.5,
'bar' => 'abc'
],
[
'foo' => 7.7,
'bar' => 'xyz'
],
[
'foo' => 2.2,
'bar' => 'efg'
]
];
// Sort $things by 'foo' property, ascending
usort($things, function ($a, $b) {
return $a['foo'] <=> $b['foo'];
});
// Sort $things by 'bar' property, descending
usort($things, function ($a, $b) {
return $b['bar'] <=> $a['bar'];
});
More examples of comparison functions written using the spaceship operator can be found in the Usefulness section of the RFC.

Its a new operator for combined comparison. Similar to strcmp() or version_compare() in behavior, but it can be used on all generic PHP values with the same semantics as <, <=, ==, >=, >. It returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater. It uses exactly the same comparison rules as used by our existing comparison operators: <, <=, ==, >= and >.
click here to know more

Related

PHP Error - usort(): Returning bool from comparison function is deprecated, return an integer less than, equal to, or greater than zero [duplicate]

the code
<?php
$consts = get_defined_constants();
$consts = array_keys($consts);
usort($consts,function($a,$b){return (int)(strlen($a)<strlen($b));});
foreach($consts as $const){
echo strlen($const).": ".$const."\n";
}
will, prior to PHP 8.0.0, print all defined constants from longest to shortest, as i expected. 7.3.13 starts with
62: SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE
62: SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE
60: SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_SENSITIVE
60: SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_SENSITIVE
51: SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_STRPREFIX
but i have no idea what PHP8.0.0 did, it's output starts with:
9: E_WARNING
21: FILTER_FLAG_STRIP_LOW
7: E_ERROR
26: FILTER_FLAG_STRIP_BACKTICK
you can see it yourself on 3v4l: https://3v4l.org/MP2IF
so what happened in PHP 8.0.0 to break this code?
Most of the other answers here are focused around how to fix the problem, but I thought I'd try and explain why this changed in PHP 8, which I think is what you're interested in.
PHP 8 introduced the Stable Sorting RFC, which (as it sounds) means that all sorting functions in PHP are now "stable". More details about this in the link.
The other answers covered this well already, but your function returns either zero or a number greater than zero. Previous implementations of sorting in PHP (in all versions lower than 8) considered zero and a negative number the same; as the RFC above mentions, the check was simply for a number greater than zero, or not. Returning zero would mean that these elements were treated the same as the case where $a < $b.
PHP introduced a deprecation warning so that a lot of sorting implementations that return booleans would still work. The RFC gives some more details on this, but importantly it means PHP 8 is still backwards compatible with them (hence this being a deprecation notice, rather than a warning). The edge-case here is that while your function effectively returns a boolean - 0 for the same length, and 1 for the case where $a < $b - because you cast this to an integer, the backwards-compatibility check in PHP 8 does not catch it, and so all "equal" elements are considered as though $a < $b
Compare:
function($a, $b) { return (int) (strlen($a) < strlen($b)); }
As in the question - works correctly in PHP <8, but raises no deprecation notice. https://3v4l.org/MP2IF
function($a, $b) { return strlen($a) < strlen($b); }
Returns a boolean, so the backwards-compatibility check in PHP 8 works correctly. But a deprecation notice is now raised. https://3v4l.org/fWR2Y
function($a, $b) { return strlen($b) <=> strlen($a); }
The "correct" solution, working correctly in all versions (at least since the spaceship operator was introduced). https://3v4l.org/6XRYW
It's because you are returning either 0 or 1, not -1.
You should use the spaceship operator instead:
https://3v4l.org/PLYAP
usort($consts, function($a, $b) {
return strlen($b) <=> strlen($a);
});
0 should be returned in case both sides are equal.
I don't know what changed internally to cause this difference, but your sorting callback is a bit funky. It should only be returning 0 if $a and $b are functionally "equal" (in this case, if they have the same string lengths). Otherwise it should return 1 if $a should sort before $b, or -1 otherwise. If I tweak your callback appropriately, I get expected output.
usort($consts, function($a, $b) {
$aLen = strlen($a);
$bLen = strlen($b);
if ($aLen === $bLen) {
return 0;
}
return $aLen < $bLen ? 1 : -1;
});
3v4l: https://3v4l.org/UScFO

The difference between PHP operators [duplicate]

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 "==="
What should I do here?
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 for the help others provided.
The List
If your particular token is not listed below, you might find it in the List of Parser Tokens.
& Bitwise Operators or References
What does it mean to start a PHP function with an ampersand?
Understanding PHP & (ampersand, bitwise and) operator
PHP "&" operator
Difference between & and && in PHP
What does "&" mean here in PHP?
What does "&" mean in this case?
What does the "&" sign mean in PHP?
What does this signature mean (&) in PHP?
How does the "&" operator work in a PHP function?
What does & in &2 mean in PHP?
When should I use a bitwise operator?
Is there ever a need to use ampersand in front of an object? (&$)
=& References
Reference assignment operator in PHP, =&
What do the "=&" and "&=" operators in PHP mean?
What do the '&=' and '=&' operators do?
What does =& mean in PHP?
&= Bitwise Operators
What do the "=&" and "&=" operators in PHP mean?
What do the '&=' and '=&' operators do?
&& Logical Operators
'AND' vs '&&' as operator
Difference between & and && in PHP
Is there any difference between "and" and "&&" operators in PHP?
PHP - and / or keywords
% Arithmetic Operators
What does the percent sign mean in PHP?
What is the PHP operator % and how do I use it in real-world examples?
!! Logical Operators
Double not (!!) operator in PHP
# Error Control Operators
What is the use of the # symbol in PHP?
'At' symbol before variable name in PHP: #$_POST
PHP functions and #functions
Should I use # in my PHP code?
What does # mean in PHP?
?: Ternary Operator
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
?? Null Coalesce Operator (since PHP 7)
C#'s null coalescing operator (??) in PHP
?string
?int
?array
?bool
?float Nullable return type declaration (since PHP 7.1)
Nullable return type declaration
Nullable parameter type declaration
php method argument type hinting with question mark (?type)
: Alternative syntax for control structures, Ternary Operator, Return Type Declaration
What is ":" in PHP?
What does ":" mean in PHP?
Colon after method declaration?
:: Scope Resolution Operator
What do two colons mean in PHP?
What's the meaning of the PHP token name T_PAAMAYIM_NEKUDOTAYIM?
What's the difference between :: (double colon) and -> (arrow) in PHP?
What exactly are late static bindings in PHP?
static::staticFunctionName()
Unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting T_NS_Separator
\ Namespaces
Backslash in PHP -- what does it mean?
What does a \ (backslash) do in PHP (5.3+)?
-> Classes And Objects
What is the "->" PHP operator called?
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
What does "=>" mean in PHP?
Use of => in PHP
What does $k => $v in foreach($ex as $k=>$v) mean?
^ Bitwise Operators
How does the bitwise operator XOR ('^') work?
What does ^ mean in PHP?
>> Bitwise Operators
What does >> mean in PHP?
<< Bitwise Operators
Strange print behaviour in PHP?
<<< Heredoc or Nowdoc
What does <<<END mean in PHP?
PHP expression <<<EOB
In PHP, what does "<<<" represent?
Using <<<CON in PHP
What's this kind of syntax in PHP?
= Assignment Operators
The 3 different equals
== 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
What does "===" mean?
How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?
The 3 different equals
Type-juggling and (strict) greater/lesser-than comparisons in PHP
!== Comparison Operators
What does !== comparison operator in PHP mean?
Is there a difference between !== and != in PHP?
!= Comparison Operators
PHP != and == operators
Is there a difference between !== and != in PHP?
comparing, !== versus !=
What is the difference between <> and !=
<> Comparison Operators
PHP operator <>
PHP's <> operator
What is the difference between <> and !=
Type-juggling and (strict) greater/lesser-than comparisons in PHP
<=> Comparison Operators (since PHP 7.0)
Spaceship (three way comparison) operator
| Bitwise Operators
What is the difference between the | and || operators?
What Does Using A Single Pipe '|' In A Function Argument Do?
|| Logical Operators
What is the difference between the | and || operators?
PHP - and / or keywords
What exactly does || mean?
The behaviour of the or operator in PHP
~ Bitwise Operators
What does this ~ operator mean here?
+ Arithmetic Operators, Array Operators
+ operator for array in PHP?
+= and -= Assignment Operators
What is += used for?
What does `$page -= 1` in my PHP document mean?
++ and -- Incrementing/Decrementing Operators
Understanding Incrementing
Answer below
.= Assignment Operators
What is the difference between .= and += in PHP?
To understand a line of PHP
. String Operators
Difference between period and comma when concatenating with echo versus return?
What does a . (dot) do in PHP?
, Function Arguments
Difference between period and comma when concatenating with echo versus return?
, Variable Declarations
What do commas mean in a variable declaration?
$$ Variable Variables
What does $$ (dollar dollar or double dollar) mean in PHP?
what is "$$" in PHP
$function() and $$variable
` Execution Operator
What are the backticks `` called?
<?= Short Open Tags
What does this symbol mean in PHP <?=
What does '<?=' mean in PHP?
What does <?= mean?
[] Arrays (short syntax since PHP 5.4)
PHP arrays... What is/are the meaning(s) of an empty bracket?
What is the meaning of []
Php array_push() vs myArray[]
What does [] mean when reading from a PHP array?
Shorthand for arrays: literal $var = [] empty array
<? Opening and Closing tags
Are PHP short tags acceptable to use?
.. Double-dot character range
Native PHP functions that allow double-dot range syntax
... Argument unpacking (since PHP 5.6)
** Exponentiation (since PHP 5.6)
# One-line shell-style comment
Can I use hashes for comments in PHP?
?-> NullSafe Operator Calls (since PHP 8.0)
Is there a "nullsafe operator" in PHP?
Incrementing / Decrementing Operators
++ increment operator
-- decrement operator
Example Name Effect
---------------------------------------------------------------------
++$a Pre-increment Increments $a by one, then returns $a.
$a++ Post-increment Returns $a, then increments $a by one.
--$a Pre-decrement Decrements $a by one, then returns $a.
$a-- Post-decrement Returns $a, then decrements $a by one.
These can go before or after the variable.
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++;
}
Once z is reached aa is next, and so on.
Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.
Stack Overflow Posts:
Understanding Incrementing
Bitwise Operator
What is a bit? A bit is a representation of 1 or 0. Basically OFF(0) and ON(1)
What is a byte? A byte is made up of 8 bits and the highest value of a byte is 255, which would mean every bit is set. We will look at why a byte's maximum value is 255.
-------------------------------------------
| 1 Byte ( 8 bits ) |
-------------------------------------------
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|
-------------------------------------------
This representation of 1 Byte
1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 = 255 (1 Byte)
A few examples for better understanding
The "AND" operator: &
$a = 9;
$b = 10;
echo $a & $b;
This would output the number 8. Why? Well let's see using our table example.
-------------------------------------------
| 1 Byte ( 8 bits ) |
-------------------------------------------
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|
-------------------------------------------
| $a | 0| 0| 0| 0| 1| 0| 0| 1|
-------------------------------------------
| $b | 0| 0| 0| 0| 1| 0| 1| 0|
-------------------------------------------
| & | 0| 0| 0| 0| 1| 0| 0| 0|
-------------------------------------------
So you can see from the table the only bit they share together is the 8 bit.
Second example
$a = 36;
$b = 103;
echo $a & $b; // This would output the number 36.
$a = 00100100
$b = 01100111
The two shared bits are 32 and 4, which when added together return 36.
The "Or" operator: |
$a = 9;
$b = 10;
echo $a | $b;
This would output the number 11. Why?
-------------------------------------------
| 1 Byte ( 8 bits ) |
-------------------------------------------
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|
-------------------------------------------
| $a | 0| 0| 0| 0| 1| 0| 0| 1|
-------------------------------------------
| $b | 0| 0| 0| 0| 1| 0| 1| 0|
-------------------------------------------
| | | 0| 0| 0| 0| 1| 0| 1| 1|
-------------------------------------------
You will notice that we have 3 bits set, in the 8, 2, and 1 columns. Add those up: 8+2+1=11.
<=> Spaceship Operator
Added in PHP 7
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.
The operator results in an integer expression of:
0 when both operands are equal
Less than 0 when the left-hand operand is less than the right-hand operand
Greater than 0 when the left-hand operand is greater than the right-hand operand
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.
Before PHP 7 you would write...
$arr = [4,2,1,3];
usort($arr, function ($a, $b) {
if ($a < $b) {
return -1;
} elseif ($a > $b) {
return 1;
} else {
return 0;
}
});
Since PHP 7 you can write...
$arr = [4,2,1,3];
usort($arr, function ($a, $b) {
return $a <=> $b;
// return $b <=> $a; // for reversing order
});
_ Alias for gettext()
The underscore character '_' as in _() is an alias to the gettext() function.
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 pairsin the same order and of the same types
x !== y
Non-identity
true if x is not identical to y
x <=> y
Spaceship
0 if x is equal to y, greater than 0 if x > y, less than 0 if x < 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. If x=6, y=3 then(x < 10 and y > 1) returns true
x && y
And
true if both x and y are true. If x=6, y=3 then(x < 10 && y > 1) returns true
x or y
Or
true if any of x or y are true. If x=6, y=3 then(x < 10 or y > 10) returns true
x || y
Or
true if any of x or y are true. If x=6, y=3 then(x < 3 || y > 1) returns true
a . b
Concatenation
Concatenate two strings: "Hi" . "Ha"
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.
__LINE__: The current line number of the file.
__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
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);
The above example will output:
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
Example with inheritance
<?php
class pclass { }
class childclass extends pclass { }
$a = new childclass;
var_dump($a instanceof childclass);
var_dump($a instanceof pclass);
The above example will output:
bool(true)
bool(true)
Example with Clone
<?php
class cloneable { }
$a = new cloneable;
$b = clone $a;
var_dump($a instanceof cloneable);
var_dump($b instanceof cloneable);
The above example will output:
bool(true)
bool(true)
An overview of operators in PHP:
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.
$a ? $b : $c : if $a return $b else return $c (ternary operator)
$a ?? $c : Same as $a ? $a : $c (null coalescing operator - requires 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
$a ??= $b : The value of $b is assigned to $a if $a is null or not defined (null coalescing assignment operator - requires PHP>=7.4)
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 a way known from languages like C, Java or JavaScript.
Spaceship Operator <=> (Added in PHP 7)
Examples for <=> Spaceship operator (PHP 7, Source: PHP Manual):
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
// Comparison is case-sensitive
echo "B" <=> "a"; // -1
echo "a" <=> "aa"; // -1
echo "zz" <=> "aa"; // 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
$a = (object) ["a" => "b"];
$b = (object) ["a" => "c"];
echo $a <=> $b; // -1
$a = (object) ["a" => "c"];
$b = (object) ["a" => "b"];
echo $a <=> $b; // 1
// only values are compared
$a = (object) ["a" => "b"];
$b = (object) ["b" => "b"];
echo $a <=> $b; // 1
{} Curly braces
Blocks - curly braces/no curly braces?
Curly braces in string in PHP
PHP curly braces in array notation
And some words about last post
$x[4] = 'd'; // it works
$x{4} = 'd'; // it works
$echo $x[4]; // it works
$echo $x{4}; // it works
$x[] = 'e'; // it works
$x{} = 'e'; // does not work
$x = [1, 2]; // it works
$x = {1, 2}; // does not work
echo "${x[4]}"; // it works
echo "${x{4}}"; // does not work
echo "{$x[4]}"; // it works
echo "{$x{4}}"; // it works
Null coalescing operator (??)
This operator has been added in PHP 7.0 for the common case of needing to use a ternary operator in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>
PHP Strings:
PHP Strings can be specified in four ways not just two ways:
1) Single Quote Strings:
$string = 'This is my string'; // print This is my string
2) Double Quote Strings:
$str = 'string';
$string = "This is my $str"; // print This is my string
3) Heredoc:
$string = <<<EOD
This is my string
EOD; // print This is my string
4) Nowdoc (since PHP 5.3.0):
$string = <<<'END_OF_STRING'
This is my string
END_OF_STRING; // print This is my string
QUESTION:
What does => mean?
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:
$myArray1 = array(2016, "hello", 33);//option 1
$myArray2 = [2016, "hello", 33];//option 2
$myArray3 = [];//option 3
$myArray3[] = 2016;
$myArray3[] = "hello";
$myArray3[] = 33;
Where as, if we wanted to call the array in some later part of the code, we could do:
echo $myArray1[1];// output: hello
echo $myArray2[1];// output: hello
echo $myArray3[1];// output: hello
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).
Differences (between a sequential and associative array):
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:
echo $myArray1["Greetings"];// output: hello
echo $myArray2["Greetings"];// output: hello
echo $myArray3["Greetings"];// output: hello
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:
What does "&" mean here in PHP?
PHP "&" operator
Makes life more easier once we get used to it..(check example below carefully)
& usually checks bits that are set in both $a and $b are set.
have you even noticed how these calls works?
error_reporting(E_ERROR | E_WARNING | E_PARSE);
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
error_reporting(E_ALL & ~E_NOTICE);
error_reporting(E_ALL);
So behind all above is game of bitwise operator and bits.
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.
Example That you 'll love
<?php
class Config {
// our constants must be 1,2,4,8,16,32,64 ....so on
const TYPE_CAT=1;
const TYPE_DOG=2;
const TYPE_LION=4;
const TYPE_RAT=8;
const TYPE_BIRD=16;
const TYPE_ALL=31;
private $config;
public function __construct($config){
$this->config=$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";
}
private function is($value){
return $this->config & $value;
}
}
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
== is used for check equality without considering variable data-type
=== is used for check equality for both the variable value and data-type
Example
$a = 5
if ($a == 5) - will evaluate to true
if ($a == '5') - will evaluate to true, because while comparing this both value PHP internally convert that string value into integer and then compare both values
if ($a === 5) - will evaluate to true
if ($a === '5') - will evaluate to false, because value is 5, but this value 5 is not an integer.
Null Coalesce operator "??" (Added in PHP 7)
Not the catchiest name for an operator, but PHP 7 brings in the rather handy null coalesce so I thought I'd share an example.
In PHP 5, we already have a ternary operator, which tests a value, and then returns the second element if that returns true and the third if it doesn't:
echo $count ? $count : 10; // outputs 10
There is also a shorthand for that which allows you to skip the second element if it's the same as the first one: echo $count ?: 10; // also outputs 10
In PHP 7 we additionally get the ?? operator which rather than indicating extreme confusion which is how I would usually use two question marks together instead allows us to chain together a string of values. Reading from left to right, the first value which exists and is not null is the value that will be returned.
// $a is not set
$b = 16;
echo $a ?? 2; // outputs 2
echo $a ?? $b ?? 7; // outputs 16
This construct is useful for giving priority to one or more values coming perhaps from user input or existing configuration, and safely falling back on a given default if that configuration is missing. It's kind of a small feature but it's one that I know I'll be using as soon as my applications upgrade to PHP 7.
Nullable return type declaration
PHP 7 adds support for return type declarations. Similarly to argument type declarations, return type declarations specify the type of value that will be returned from a function. The same types are available for return type declarations as are available for argument type declarations.
Strict typing also has an effect on return type declarations. In the default weak mode, returned values will be coerced to the correct type if they are not already of that type. In strong mode, the returned value must be of the correct type, otherwise, a TypeError will be thrown.
As of PHP 7.1.0, return values can be marked as nullable by prefixing the type name with a question mark (?). This signifies that the function returns either the specified type or NULL.
<?php
function get_item(): ?string {
if (isset($_GET['item'])) {
return $_GET['item'];
} else {
return null;
}
}
?>
Source
?-> NullSafe Operator
Added in PHP 8.0
It's the NullSafe Operator, it returns null in case you try to invoke functions or get values from null. Nullsafe operator can be chained and can be used both on the methods and properties.
$objDrive = null;
$drive = $objDrive?->func?->getDriver()?->value; //return null
$drive = $objDrive->func->getDriver()->value; // Error: Trying to get property 'func' of non-object
Nullsafe operator doesn't work with array keys:
$drive['admin']?->getDriver()?->value //Warning: Trying to access array offset on value of type null
$drive = [];
$drive['admin']?->getAddress()?->value //Warning: Undefined array key "admin"
Three DOTS as Splat Operator (...) (since PHP 5.6)
PHP has an operator "..." (Three dots) which is referred as Splat Operator. It is used to pass arbitrary number of parameters in a function and this type of function is called Variadic Functions. Let’s take examples to use of "..." (Three dots).
Example 1:
<?php
function calculateNumbers(...$params){
$total = 0;
foreach($params as $v){
$total = $total + $v;
}
return $total;
}
echo calculateNumbers(10, 20, 30, 40, 50);
//Output 150
?>
Each arguments of calculateNumbers() function pass through $params as an array when use "… ".
There are many different ways to use "… " operator. Below some examples:
Example 2:
<?php
function calculateNumbers($no1, $no2, $no3, $no4, $no5){
$total = $no1 + $no2 + $no3 + $no4 + $no5;
return $total;
}
$numbers = array(10, 20, 30, 40, 50);
echo calculateNumbers(...$numbers);
//Output 150
?>
Example 3:
<?php
function calculateNumbers(...$params){
$total = 0;
foreach($params as $v){
$total = $total + $v;
}
return $total;
}
$no1 = 70;
$numbers = array(10, 20, 30, 40, 50);
echo calculateNumbers($no1, ...$numbers);
//Output 220
?>
Example 4:
<?php
function calculateNumbers(...$params){
$total = 0;
foreach($params as $v){
$total = $total + $v;
}
return $total;
}
$numbers1 = array(10, 20, 30, 40, 50);
$numbers2 = array(100, 200, 300, 400, 500);
echo calculateNumbers(...$numbers1, ...$numbers2);
//Output 1650
?>
It should be noted that Variadic Parameters cannot be targeted by named arguments.
Example 5:
<?php
function sumIntegers(int ...$params): int {
$sum = 0;
foreach($params as $value){
$sum += $value;
}
return $sum;
}
echo sumIntegers(params: [1, 2, 3, 4]);
// $params will be equal to ['params' => [1, 2, 3, 4]] in sumIntegers
// throws TypeError sumIntegers(): Argument #1 must be of type int, array given
echo sumIntegers(arbitrary_name: 1, another_name: 2);
// $params will be equal to ['arbitrary_name' => 1, 'another_name' => 2] in sumIntegers
// Outputs: 3
?>
Using an unpacked associative array as the parameter for a function call has the same effect as calling the function using each key-value pair as a named argument.
Example 6:
<?php
function fullName(string $first_name, ?string $middle_name = null, ?string $last_name = null): string {
return trim("$first_name|$middle_name|$last_name");
}
$params = ['first_name' => 'John', 'last_name' => 'Doe'];
echo fullName(...$params);
// same as fullName(first_name: 'John', last_name: 'Doe')
// outputs 'John||Doe'
?>
This can be used to pass named arguments to something like a nested function call or a class.
Example 7:
<?php
function throw_exception(string $exception, ...$parameters) {
throw new $exception(...$parameters);
}
throw_exception(exception: 'Exception', code: 123);
// executes throw new Exception(...['code' => 123])
// which is the same as throw new Exception(code: 123);
?>
NullSafe Operator "?->" since php8
In PHP8 it's been accepted this new operator, you can find the documentation here. ?-> it's the NullSafe Operator, it returns null in case you try to invoke functions or get values from null...
Examples:
<?php
$obj = null;
$obj = $obj?->attr; //return null
$obj = ?->funct(); // return null
$obj = $objDrive->attr; // Error: Trying to get property 'attr' of non-object
?>
#[] attributes since PHP 8
You can write #[attribute_name] since PHP 8. This is an attribute in PHP (also Rust and C#). Other languages may use names like annotations (Java) or decorators (Python, Javascript) for a similar feature. Prior to PHP 8, #[whatever] would have been a comment until the end of the line (because # starts a comment in PHP). So if an attribute is the last thing on a line, it will be ignored in versions before PHP 8. If not the last thing on a line, it would comment out whatever was after it prior to PHP 8 (since then the ] terminates it).
RFC
Syntax RFC (the syntax was changed from the original RFC)
Documentation
In php 8
Instead of writing the classic !== null you can use the ? operator to write just 1 line of code, the code becomes pretty clear:
Before:
$firsName = null;
if ($session !== null) {
$user = $session->user;
if ($user !== null) {
$name = $user->getName();
if ($name !== null) {
$firstName = $name->firstName;
}
}
}
After:
$firsName = $session?->user?->getName()?->firstName;
Use match instead of switch. The match expression uses strict comparison (===) instead. The comparison is strict regardless of strict_types.
Before:
switch ('A') {
case 'A':
echo "found A";
break;
case 'B':
echo "found B";
break;
}
// Result: "found A"
After:
echo match ('A') {
'A' => "found A",
'B' => "found B",
};
// Result: "found A"
Double-dot syntax
When used between two characters in qualifying native PHP string functions, .. acts to express an inclusive range of characters. a-e is equivalent to abcde.
echo trim('adobe', 'a..e');
Prints:
o
Native PHP functions that allow double-dot range syntax
What does \ (backslash) symbol in PHP
It uses for to escape string type or to change specific case:
Examples:
Here \r\n and \n using for pass to new line (like enter button)
echo "Hello world \n\r I am Herakl";
Alternatively, you can use PHP_EOL. There are some exceptions. Firstly, it can use only in two quotes (") condition. Also, it is escape self
echo " Hello \\ I am robot";
In stackoverflow it doesn't see correctly.
Backslashes also use in namespaces or use condition names:
namespace App\Http\Controllers;
use App\Models;
Additionally, you should visit about slashes https://www.php.net/manual/en/function.addslashes.php

PHP append content between comments in .htaccess file without duplicates [duplicate]

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 "==="
What should I do here?
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 for the help others provided.
The List
If your particular token is not listed below, you might find it in the List of Parser Tokens.
& Bitwise Operators or References
What does it mean to start a PHP function with an ampersand?
Understanding PHP & (ampersand, bitwise and) operator
PHP "&" operator
Difference between & and && in PHP
What does "&" mean here in PHP?
What does "&" mean in this case?
What does the "&" sign mean in PHP?
What does this signature mean (&) in PHP?
How does the "&" operator work in a PHP function?
What does & in &2 mean in PHP?
When should I use a bitwise operator?
Is there ever a need to use ampersand in front of an object? (&$)
=& References
Reference assignment operator in PHP, =&
What do the "=&" and "&=" operators in PHP mean?
What do the '&=' and '=&' operators do?
What does =& mean in PHP?
&= Bitwise Operators
What do the "=&" and "&=" operators in PHP mean?
What do the '&=' and '=&' operators do?
&& Logical Operators
'AND' vs '&&' as operator
Difference between & and && in PHP
Is there any difference between "and" and "&&" operators in PHP?
PHP - and / or keywords
% Arithmetic Operators
What does the percent sign mean in PHP?
What is the PHP operator % and how do I use it in real-world examples?
!! Logical Operators
Double not (!!) operator in PHP
# Error Control Operators
What is the use of the # symbol in PHP?
'At' symbol before variable name in PHP: #$_POST
PHP functions and #functions
Should I use # in my PHP code?
What does # mean in PHP?
?: Ternary Operator
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
?? Null Coalesce Operator (since PHP 7)
C#'s null coalescing operator (??) in PHP
?string
?int
?array
?bool
?float Nullable return type declaration (since PHP 7.1)
Nullable return type declaration
Nullable parameter type declaration
php method argument type hinting with question mark (?type)
: Alternative syntax for control structures, Ternary Operator, Return Type Declaration
What is ":" in PHP?
What does ":" mean in PHP?
Colon after method declaration?
:: Scope Resolution Operator
What do two colons mean in PHP?
What's the meaning of the PHP token name T_PAAMAYIM_NEKUDOTAYIM?
What's the difference between :: (double colon) and -> (arrow) in PHP?
What exactly are late static bindings in PHP?
static::staticFunctionName()
Unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting T_NS_Separator
\ Namespaces
Backslash in PHP -- what does it mean?
What does a \ (backslash) do in PHP (5.3+)?
-> Classes And Objects
What is the "->" PHP operator called?
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
What does "=>" mean in PHP?
Use of => in PHP
What does $k => $v in foreach($ex as $k=>$v) mean?
^ Bitwise Operators
How does the bitwise operator XOR ('^') work?
What does ^ mean in PHP?
>> Bitwise Operators
What does >> mean in PHP?
<< Bitwise Operators
Strange print behaviour in PHP?
<<< Heredoc or Nowdoc
What does <<<END mean in PHP?
PHP expression <<<EOB
In PHP, what does "<<<" represent?
Using <<<CON in PHP
What's this kind of syntax in PHP?
= Assignment Operators
The 3 different equals
== 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
What does "===" mean?
How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?
The 3 different equals
Type-juggling and (strict) greater/lesser-than comparisons in PHP
!== Comparison Operators
What does !== comparison operator in PHP mean?
Is there a difference between !== and != in PHP?
!= Comparison Operators
PHP != and == operators
Is there a difference between !== and != in PHP?
comparing, !== versus !=
What is the difference between <> and !=
<> Comparison Operators
PHP operator <>
PHP's <> operator
What is the difference between <> and !=
Type-juggling and (strict) greater/lesser-than comparisons in PHP
<=> Comparison Operators (since PHP 7.0)
Spaceship (three way comparison) operator
| Bitwise Operators
What is the difference between the | and || operators?
What Does Using A Single Pipe '|' In A Function Argument Do?
|| Logical Operators
What is the difference between the | and || operators?
PHP - and / or keywords
What exactly does || mean?
The behaviour of the or operator in PHP
~ Bitwise Operators
What does this ~ operator mean here?
+ Arithmetic Operators, Array Operators
+ operator for array in PHP?
+= and -= Assignment Operators
What is += used for?
What does `$page -= 1` in my PHP document mean?
++ and -- Incrementing/Decrementing Operators
Understanding Incrementing
Answer below
.= Assignment Operators
What is the difference between .= and += in PHP?
To understand a line of PHP
. String Operators
Difference between period and comma when concatenating with echo versus return?
What does a . (dot) do in PHP?
, Function Arguments
Difference between period and comma when concatenating with echo versus return?
, Variable Declarations
What do commas mean in a variable declaration?
$$ Variable Variables
What does $$ (dollar dollar or double dollar) mean in PHP?
what is "$$" in PHP
$function() and $$variable
` Execution Operator
What are the backticks `` called?
<?= Short Open Tags
What does this symbol mean in PHP <?=
What does '<?=' mean in PHP?
What does <?= mean?
[] Arrays (short syntax since PHP 5.4)
PHP arrays... What is/are the meaning(s) of an empty bracket?
What is the meaning of []
Php array_push() vs myArray[]
What does [] mean when reading from a PHP array?
Shorthand for arrays: literal $var = [] empty array
<? Opening and Closing tags
Are PHP short tags acceptable to use?
.. Double-dot character range
Native PHP functions that allow double-dot range syntax
... Argument unpacking (since PHP 5.6)
** Exponentiation (since PHP 5.6)
# One-line shell-style comment
Can I use hashes for comments in PHP?
?-> NullSafe Operator Calls (since PHP 8.0)
Is there a "nullsafe operator" in PHP?
Incrementing / Decrementing Operators
++ increment operator
-- decrement operator
Example Name Effect
---------------------------------------------------------------------
++$a Pre-increment Increments $a by one, then returns $a.
$a++ Post-increment Returns $a, then increments $a by one.
--$a Pre-decrement Decrements $a by one, then returns $a.
$a-- Post-decrement Returns $a, then decrements $a by one.
These can go before or after the variable.
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++;
}
Once z is reached aa is next, and so on.
Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.
Stack Overflow Posts:
Understanding Incrementing
Bitwise Operator
What is a bit? A bit is a representation of 1 or 0. Basically OFF(0) and ON(1)
What is a byte? A byte is made up of 8 bits and the highest value of a byte is 255, which would mean every bit is set. We will look at why a byte's maximum value is 255.
-------------------------------------------
| 1 Byte ( 8 bits ) |
-------------------------------------------
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|
-------------------------------------------
This representation of 1 Byte
1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 = 255 (1 Byte)
A few examples for better understanding
The "AND" operator: &
$a = 9;
$b = 10;
echo $a & $b;
This would output the number 8. Why? Well let's see using our table example.
-------------------------------------------
| 1 Byte ( 8 bits ) |
-------------------------------------------
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|
-------------------------------------------
| $a | 0| 0| 0| 0| 1| 0| 0| 1|
-------------------------------------------
| $b | 0| 0| 0| 0| 1| 0| 1| 0|
-------------------------------------------
| & | 0| 0| 0| 0| 1| 0| 0| 0|
-------------------------------------------
So you can see from the table the only bit they share together is the 8 bit.
Second example
$a = 36;
$b = 103;
echo $a & $b; // This would output the number 36.
$a = 00100100
$b = 01100111
The two shared bits are 32 and 4, which when added together return 36.
The "Or" operator: |
$a = 9;
$b = 10;
echo $a | $b;
This would output the number 11. Why?
-------------------------------------------
| 1 Byte ( 8 bits ) |
-------------------------------------------
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|
-------------------------------------------
| $a | 0| 0| 0| 0| 1| 0| 0| 1|
-------------------------------------------
| $b | 0| 0| 0| 0| 1| 0| 1| 0|
-------------------------------------------
| | | 0| 0| 0| 0| 1| 0| 1| 1|
-------------------------------------------
You will notice that we have 3 bits set, in the 8, 2, and 1 columns. Add those up: 8+2+1=11.
<=> Spaceship Operator
Added in PHP 7
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.
The operator results in an integer expression of:
0 when both operands are equal
Less than 0 when the left-hand operand is less than the right-hand operand
Greater than 0 when the left-hand operand is greater than the right-hand operand
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.
Before PHP 7 you would write...
$arr = [4,2,1,3];
usort($arr, function ($a, $b) {
if ($a < $b) {
return -1;
} elseif ($a > $b) {
return 1;
} else {
return 0;
}
});
Since PHP 7 you can write...
$arr = [4,2,1,3];
usort($arr, function ($a, $b) {
return $a <=> $b;
// return $b <=> $a; // for reversing order
});
_ Alias for gettext()
The underscore character '_' as in _() is an alias to the gettext() function.
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 pairsin the same order and of the same types
x !== y
Non-identity
true if x is not identical to y
x <=> y
Spaceship
0 if x is equal to y, greater than 0 if x > y, less than 0 if x < 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. If x=6, y=3 then(x < 10 and y > 1) returns true
x && y
And
true if both x and y are true. If x=6, y=3 then(x < 10 && y > 1) returns true
x or y
Or
true if any of x or y are true. If x=6, y=3 then(x < 10 or y > 10) returns true
x || y
Or
true if any of x or y are true. If x=6, y=3 then(x < 3 || y > 1) returns true
a . b
Concatenation
Concatenate two strings: "Hi" . "Ha"
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.
__LINE__: The current line number of the file.
__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
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);
The above example will output:
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
Example with inheritance
<?php
class pclass { }
class childclass extends pclass { }
$a = new childclass;
var_dump($a instanceof childclass);
var_dump($a instanceof pclass);
The above example will output:
bool(true)
bool(true)
Example with Clone
<?php
class cloneable { }
$a = new cloneable;
$b = clone $a;
var_dump($a instanceof cloneable);
var_dump($b instanceof cloneable);
The above example will output:
bool(true)
bool(true)
An overview of operators in PHP:
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.
$a ? $b : $c : if $a return $b else return $c (ternary operator)
$a ?? $c : Same as $a ? $a : $c (null coalescing operator - requires 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
$a ??= $b : The value of $b is assigned to $a if $a is null or not defined (null coalescing assignment operator - requires PHP>=7.4)
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 a way known from languages like C, Java or JavaScript.
Spaceship Operator <=> (Added in PHP 7)
Examples for <=> Spaceship operator (PHP 7, Source: PHP Manual):
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
// Comparison is case-sensitive
echo "B" <=> "a"; // -1
echo "a" <=> "aa"; // -1
echo "zz" <=> "aa"; // 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
$a = (object) ["a" => "b"];
$b = (object) ["a" => "c"];
echo $a <=> $b; // -1
$a = (object) ["a" => "c"];
$b = (object) ["a" => "b"];
echo $a <=> $b; // 1
// only values are compared
$a = (object) ["a" => "b"];
$b = (object) ["b" => "b"];
echo $a <=> $b; // 1
{} Curly braces
Blocks - curly braces/no curly braces?
Curly braces in string in PHP
PHP curly braces in array notation
And some words about last post
$x[4] = 'd'; // it works
$x{4} = 'd'; // it works
$echo $x[4]; // it works
$echo $x{4}; // it works
$x[] = 'e'; // it works
$x{} = 'e'; // does not work
$x = [1, 2]; // it works
$x = {1, 2}; // does not work
echo "${x[4]}"; // it works
echo "${x{4}}"; // does not work
echo "{$x[4]}"; // it works
echo "{$x{4}}"; // it works
Null coalescing operator (??)
This operator has been added in PHP 7.0 for the common case of needing to use a ternary operator in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>
PHP Strings:
PHP Strings can be specified in four ways not just two ways:
1) Single Quote Strings:
$string = 'This is my string'; // print This is my string
2) Double Quote Strings:
$str = 'string';
$string = "This is my $str"; // print This is my string
3) Heredoc:
$string = <<<EOD
This is my string
EOD; // print This is my string
4) Nowdoc (since PHP 5.3.0):
$string = <<<'END_OF_STRING'
This is my string
END_OF_STRING; // print This is my string
QUESTION:
What does => mean?
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:
$myArray1 = array(2016, "hello", 33);//option 1
$myArray2 = [2016, "hello", 33];//option 2
$myArray3 = [];//option 3
$myArray3[] = 2016;
$myArray3[] = "hello";
$myArray3[] = 33;
Where as, if we wanted to call the array in some later part of the code, we could do:
echo $myArray1[1];// output: hello
echo $myArray2[1];// output: hello
echo $myArray3[1];// output: hello
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).
Differences (between a sequential and associative array):
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:
echo $myArray1["Greetings"];// output: hello
echo $myArray2["Greetings"];// output: hello
echo $myArray3["Greetings"];// output: hello
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:
What does "&" mean here in PHP?
PHP "&" operator
Makes life more easier once we get used to it..(check example below carefully)
& usually checks bits that are set in both $a and $b are set.
have you even noticed how these calls works?
error_reporting(E_ERROR | E_WARNING | E_PARSE);
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
error_reporting(E_ALL & ~E_NOTICE);
error_reporting(E_ALL);
So behind all above is game of bitwise operator and bits.
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.
Example That you 'll love
<?php
class Config {
// our constants must be 1,2,4,8,16,32,64 ....so on
const TYPE_CAT=1;
const TYPE_DOG=2;
const TYPE_LION=4;
const TYPE_RAT=8;
const TYPE_BIRD=16;
const TYPE_ALL=31;
private $config;
public function __construct($config){
$this->config=$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";
}
private function is($value){
return $this->config & $value;
}
}
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
== is used for check equality without considering variable data-type
=== is used for check equality for both the variable value and data-type
Example
$a = 5
if ($a == 5) - will evaluate to true
if ($a == '5') - will evaluate to true, because while comparing this both value PHP internally convert that string value into integer and then compare both values
if ($a === 5) - will evaluate to true
if ($a === '5') - will evaluate to false, because value is 5, but this value 5 is not an integer.
Null Coalesce operator "??" (Added in PHP 7)
Not the catchiest name for an operator, but PHP 7 brings in the rather handy null coalesce so I thought I'd share an example.
In PHP 5, we already have a ternary operator, which tests a value, and then returns the second element if that returns true and the third if it doesn't:
echo $count ? $count : 10; // outputs 10
There is also a shorthand for that which allows you to skip the second element if it's the same as the first one: echo $count ?: 10; // also outputs 10
In PHP 7 we additionally get the ?? operator which rather than indicating extreme confusion which is how I would usually use two question marks together instead allows us to chain together a string of values. Reading from left to right, the first value which exists and is not null is the value that will be returned.
// $a is not set
$b = 16;
echo $a ?? 2; // outputs 2
echo $a ?? $b ?? 7; // outputs 16
This construct is useful for giving priority to one or more values coming perhaps from user input or existing configuration, and safely falling back on a given default if that configuration is missing. It's kind of a small feature but it's one that I know I'll be using as soon as my applications upgrade to PHP 7.
Nullable return type declaration
PHP 7 adds support for return type declarations. Similarly to argument type declarations, return type declarations specify the type of value that will be returned from a function. The same types are available for return type declarations as are available for argument type declarations.
Strict typing also has an effect on return type declarations. In the default weak mode, returned values will be coerced to the correct type if they are not already of that type. In strong mode, the returned value must be of the correct type, otherwise, a TypeError will be thrown.
As of PHP 7.1.0, return values can be marked as nullable by prefixing the type name with a question mark (?). This signifies that the function returns either the specified type or NULL.
<?php
function get_item(): ?string {
if (isset($_GET['item'])) {
return $_GET['item'];
} else {
return null;
}
}
?>
Source
?-> NullSafe Operator
Added in PHP 8.0
It's the NullSafe Operator, it returns null in case you try to invoke functions or get values from null. Nullsafe operator can be chained and can be used both on the methods and properties.
$objDrive = null;
$drive = $objDrive?->func?->getDriver()?->value; //return null
$drive = $objDrive->func->getDriver()->value; // Error: Trying to get property 'func' of non-object
Nullsafe operator doesn't work with array keys:
$drive['admin']?->getDriver()?->value //Warning: Trying to access array offset on value of type null
$drive = [];
$drive['admin']?->getAddress()?->value //Warning: Undefined array key "admin"
Three DOTS as Splat Operator (...) (since PHP 5.6)
PHP has an operator "..." (Three dots) which is referred as Splat Operator. It is used to pass arbitrary number of parameters in a function and this type of function is called Variadic Functions. Let’s take examples to use of "..." (Three dots).
Example 1:
<?php
function calculateNumbers(...$params){
$total = 0;
foreach($params as $v){
$total = $total + $v;
}
return $total;
}
echo calculateNumbers(10, 20, 30, 40, 50);
//Output 150
?>
Each arguments of calculateNumbers() function pass through $params as an array when use "… ".
There are many different ways to use "… " operator. Below some examples:
Example 2:
<?php
function calculateNumbers($no1, $no2, $no3, $no4, $no5){
$total = $no1 + $no2 + $no3 + $no4 + $no5;
return $total;
}
$numbers = array(10, 20, 30, 40, 50);
echo calculateNumbers(...$numbers);
//Output 150
?>
Example 3:
<?php
function calculateNumbers(...$params){
$total = 0;
foreach($params as $v){
$total = $total + $v;
}
return $total;
}
$no1 = 70;
$numbers = array(10, 20, 30, 40, 50);
echo calculateNumbers($no1, ...$numbers);
//Output 220
?>
Example 4:
<?php
function calculateNumbers(...$params){
$total = 0;
foreach($params as $v){
$total = $total + $v;
}
return $total;
}
$numbers1 = array(10, 20, 30, 40, 50);
$numbers2 = array(100, 200, 300, 400, 500);
echo calculateNumbers(...$numbers1, ...$numbers2);
//Output 1650
?>
It should be noted that Variadic Parameters cannot be targeted by named arguments.
Example 5:
<?php
function sumIntegers(int ...$params): int {
$sum = 0;
foreach($params as $value){
$sum += $value;
}
return $sum;
}
echo sumIntegers(params: [1, 2, 3, 4]);
// $params will be equal to ['params' => [1, 2, 3, 4]] in sumIntegers
// throws TypeError sumIntegers(): Argument #1 must be of type int, array given
echo sumIntegers(arbitrary_name: 1, another_name: 2);
// $params will be equal to ['arbitrary_name' => 1, 'another_name' => 2] in sumIntegers
// Outputs: 3
?>
Using an unpacked associative array as the parameter for a function call has the same effect as calling the function using each key-value pair as a named argument.
Example 6:
<?php
function fullName(string $first_name, ?string $middle_name = null, ?string $last_name = null): string {
return trim("$first_name|$middle_name|$last_name");
}
$params = ['first_name' => 'John', 'last_name' => 'Doe'];
echo fullName(...$params);
// same as fullName(first_name: 'John', last_name: 'Doe')
// outputs 'John||Doe'
?>
This can be used to pass named arguments to something like a nested function call or a class.
Example 7:
<?php
function throw_exception(string $exception, ...$parameters) {
throw new $exception(...$parameters);
}
throw_exception(exception: 'Exception', code: 123);
// executes throw new Exception(...['code' => 123])
// which is the same as throw new Exception(code: 123);
?>
NullSafe Operator "?->" since php8
In PHP8 it's been accepted this new operator, you can find the documentation here. ?-> it's the NullSafe Operator, it returns null in case you try to invoke functions or get values from null...
Examples:
<?php
$obj = null;
$obj = $obj?->attr; //return null
$obj = ?->funct(); // return null
$obj = $objDrive->attr; // Error: Trying to get property 'attr' of non-object
?>
#[] attributes since PHP 8
You can write #[attribute_name] since PHP 8. This is an attribute in PHP (also Rust and C#). Other languages may use names like annotations (Java) or decorators (Python, Javascript) for a similar feature. Prior to PHP 8, #[whatever] would have been a comment until the end of the line (because # starts a comment in PHP). So if an attribute is the last thing on a line, it will be ignored in versions before PHP 8. If not the last thing on a line, it would comment out whatever was after it prior to PHP 8 (since then the ] terminates it).
RFC
Syntax RFC (the syntax was changed from the original RFC)
Documentation
In php 8
Instead of writing the classic !== null you can use the ? operator to write just 1 line of code, the code becomes pretty clear:
Before:
$firsName = null;
if ($session !== null) {
$user = $session->user;
if ($user !== null) {
$name = $user->getName();
if ($name !== null) {
$firstName = $name->firstName;
}
}
}
After:
$firsName = $session?->user?->getName()?->firstName;
Use match instead of switch. The match expression uses strict comparison (===) instead. The comparison is strict regardless of strict_types.
Before:
switch ('A') {
case 'A':
echo "found A";
break;
case 'B':
echo "found B";
break;
}
// Result: "found A"
After:
echo match ('A') {
'A' => "found A",
'B' => "found B",
};
// Result: "found A"
Double-dot syntax
When used between two characters in qualifying native PHP string functions, .. acts to express an inclusive range of characters. a-e is equivalent to abcde.
echo trim('adobe', 'a..e');
Prints:
o
Native PHP functions that allow double-dot range syntax
What does \ (backslash) symbol in PHP
It uses for to escape string type or to change specific case:
Examples:
Here \r\n and \n using for pass to new line (like enter button)
echo "Hello world \n\r I am Herakl";
Alternatively, you can use PHP_EOL. There are some exceptions. Firstly, it can use only in two quotes (") condition. Also, it is escape self
echo " Hello \\ I am robot";
In stackoverflow it doesn't see correctly.
Backslashes also use in namespaces or use condition names:
namespace App\Http\Controllers;
use App\Models;
Additionally, you should visit about slashes https://www.php.net/manual/en/function.addslashes.php

PHP && giving wrong answer [duplicate]

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 "==="
What should I do here?
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 for the help others provided.
The List
If your particular token is not listed below, you might find it in the List of Parser Tokens.
& Bitwise Operators or References
What does it mean to start a PHP function with an ampersand?
Understanding PHP & (ampersand, bitwise and) operator
PHP "&" operator
Difference between & and && in PHP
What does "&" mean here in PHP?
What does "&" mean in this case?
What does the "&" sign mean in PHP?
What does this signature mean (&) in PHP?
How does the "&" operator work in a PHP function?
What does & in &2 mean in PHP?
When should I use a bitwise operator?
Is there ever a need to use ampersand in front of an object? (&$)
=& References
Reference assignment operator in PHP, =&
What do the "=&" and "&=" operators in PHP mean?
What do the '&=' and '=&' operators do?
What does =& mean in PHP?
&= Bitwise Operators
What do the "=&" and "&=" operators in PHP mean?
What do the '&=' and '=&' operators do?
&& Logical Operators
'AND' vs '&&' as operator
Difference between & and && in PHP
Is there any difference between "and" and "&&" operators in PHP?
PHP - and / or keywords
% Arithmetic Operators
What does the percent sign mean in PHP?
What is the PHP operator % and how do I use it in real-world examples?
!! Logical Operators
Double not (!!) operator in PHP
# Error Control Operators
What is the use of the # symbol in PHP?
'At' symbol before variable name in PHP: #$_POST
PHP functions and #functions
Should I use # in my PHP code?
What does # mean in PHP?
?: Ternary Operator
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
?? Null Coalesce Operator (since PHP 7)
C#'s null coalescing operator (??) in PHP
?string
?int
?array
?bool
?float Nullable return type declaration (since PHP 7.1)
Nullable return type declaration
Nullable parameter type declaration
php method argument type hinting with question mark (?type)
: Alternative syntax for control structures, Ternary Operator, Return Type Declaration
What is ":" in PHP?
What does ":" mean in PHP?
Colon after method declaration?
:: Scope Resolution Operator
What do two colons mean in PHP?
What's the meaning of the PHP token name T_PAAMAYIM_NEKUDOTAYIM?
What's the difference between :: (double colon) and -> (arrow) in PHP?
What exactly are late static bindings in PHP?
static::staticFunctionName()
Unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting T_NS_Separator
\ Namespaces
Backslash in PHP -- what does it mean?
What does a \ (backslash) do in PHP (5.3+)?
-> Classes And Objects
What is the "->" PHP operator called?
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
What does "=>" mean in PHP?
Use of => in PHP
What does $k => $v in foreach($ex as $k=>$v) mean?
^ Bitwise Operators
How does the bitwise operator XOR ('^') work?
What does ^ mean in PHP?
>> Bitwise Operators
What does >> mean in PHP?
<< Bitwise Operators
Strange print behaviour in PHP?
<<< Heredoc or Nowdoc
What does <<<END mean in PHP?
PHP expression <<<EOB
In PHP, what does "<<<" represent?
Using <<<CON in PHP
What's this kind of syntax in PHP?
= Assignment Operators
The 3 different equals
== 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
What does "===" mean?
How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?
The 3 different equals
Type-juggling and (strict) greater/lesser-than comparisons in PHP
!== Comparison Operators
What does !== comparison operator in PHP mean?
Is there a difference between !== and != in PHP?
!= Comparison Operators
PHP != and == operators
Is there a difference between !== and != in PHP?
comparing, !== versus !=
What is the difference between <> and !=
<> Comparison Operators
PHP operator <>
PHP's <> operator
What is the difference between <> and !=
Type-juggling and (strict) greater/lesser-than comparisons in PHP
<=> Comparison Operators (since PHP 7.0)
Spaceship (three way comparison) operator
| Bitwise Operators
What is the difference between the | and || operators?
What Does Using A Single Pipe '|' In A Function Argument Do?
|| Logical Operators
What is the difference between the | and || operators?
PHP - and / or keywords
What exactly does || mean?
The behaviour of the or operator in PHP
~ Bitwise Operators
What does this ~ operator mean here?
+ Arithmetic Operators, Array Operators
+ operator for array in PHP?
+= and -= Assignment Operators
What is += used for?
What does `$page -= 1` in my PHP document mean?
++ and -- Incrementing/Decrementing Operators
Understanding Incrementing
Answer below
.= Assignment Operators
What is the difference between .= and += in PHP?
To understand a line of PHP
. String Operators
Difference between period and comma when concatenating with echo versus return?
What does a . (dot) do in PHP?
, Function Arguments
Difference between period and comma when concatenating with echo versus return?
, Variable Declarations
What do commas mean in a variable declaration?
$$ Variable Variables
What does $$ (dollar dollar or double dollar) mean in PHP?
what is "$$" in PHP
$function() and $$variable
` Execution Operator
What are the backticks `` called?
<?= Short Open Tags
What does this symbol mean in PHP <?=
What does '<?=' mean in PHP?
What does <?= mean?
[] Arrays (short syntax since PHP 5.4)
PHP arrays... What is/are the meaning(s) of an empty bracket?
What is the meaning of []
Php array_push() vs myArray[]
What does [] mean when reading from a PHP array?
Shorthand for arrays: literal $var = [] empty array
<? Opening and Closing tags
Are PHP short tags acceptable to use?
.. Double-dot character range
Native PHP functions that allow double-dot range syntax
... Argument unpacking (since PHP 5.6)
** Exponentiation (since PHP 5.6)
# One-line shell-style comment
Can I use hashes for comments in PHP?
?-> NullSafe Operator Calls (since PHP 8.0)
Is there a "nullsafe operator" in PHP?
Incrementing / Decrementing Operators
++ increment operator
-- decrement operator
Example Name Effect
---------------------------------------------------------------------
++$a Pre-increment Increments $a by one, then returns $a.
$a++ Post-increment Returns $a, then increments $a by one.
--$a Pre-decrement Decrements $a by one, then returns $a.
$a-- Post-decrement Returns $a, then decrements $a by one.
These can go before or after the variable.
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++;
}
Once z is reached aa is next, and so on.
Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.
Stack Overflow Posts:
Understanding Incrementing
Bitwise Operator
What is a bit? A bit is a representation of 1 or 0. Basically OFF(0) and ON(1)
What is a byte? A byte is made up of 8 bits and the highest value of a byte is 255, which would mean every bit is set. We will look at why a byte's maximum value is 255.
-------------------------------------------
| 1 Byte ( 8 bits ) |
-------------------------------------------
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|
-------------------------------------------
This representation of 1 Byte
1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 = 255 (1 Byte)
A few examples for better understanding
The "AND" operator: &
$a = 9;
$b = 10;
echo $a & $b;
This would output the number 8. Why? Well let's see using our table example.
-------------------------------------------
| 1 Byte ( 8 bits ) |
-------------------------------------------
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|
-------------------------------------------
| $a | 0| 0| 0| 0| 1| 0| 0| 1|
-------------------------------------------
| $b | 0| 0| 0| 0| 1| 0| 1| 0|
-------------------------------------------
| & | 0| 0| 0| 0| 1| 0| 0| 0|
-------------------------------------------
So you can see from the table the only bit they share together is the 8 bit.
Second example
$a = 36;
$b = 103;
echo $a & $b; // This would output the number 36.
$a = 00100100
$b = 01100111
The two shared bits are 32 and 4, which when added together return 36.
The "Or" operator: |
$a = 9;
$b = 10;
echo $a | $b;
This would output the number 11. Why?
-------------------------------------------
| 1 Byte ( 8 bits ) |
-------------------------------------------
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|
-------------------------------------------
| $a | 0| 0| 0| 0| 1| 0| 0| 1|
-------------------------------------------
| $b | 0| 0| 0| 0| 1| 0| 1| 0|
-------------------------------------------
| | | 0| 0| 0| 0| 1| 0| 1| 1|
-------------------------------------------
You will notice that we have 3 bits set, in the 8, 2, and 1 columns. Add those up: 8+2+1=11.
<=> Spaceship Operator
Added in PHP 7
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.
The operator results in an integer expression of:
0 when both operands are equal
Less than 0 when the left-hand operand is less than the right-hand operand
Greater than 0 when the left-hand operand is greater than the right-hand operand
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.
Before PHP 7 you would write...
$arr = [4,2,1,3];
usort($arr, function ($a, $b) {
if ($a < $b) {
return -1;
} elseif ($a > $b) {
return 1;
} else {
return 0;
}
});
Since PHP 7 you can write...
$arr = [4,2,1,3];
usort($arr, function ($a, $b) {
return $a <=> $b;
// return $b <=> $a; // for reversing order
});
_ Alias for gettext()
The underscore character '_' as in _() is an alias to the gettext() function.
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 pairsin the same order and of the same types
x !== y
Non-identity
true if x is not identical to y
x <=> y
Spaceship
0 if x is equal to y, greater than 0 if x > y, less than 0 if x < 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. If x=6, y=3 then(x < 10 and y > 1) returns true
x && y
And
true if both x and y are true. If x=6, y=3 then(x < 10 && y > 1) returns true
x or y
Or
true if any of x or y are true. If x=6, y=3 then(x < 10 or y > 10) returns true
x || y
Or
true if any of x or y are true. If x=6, y=3 then(x < 3 || y > 1) returns true
a . b
Concatenation
Concatenate two strings: "Hi" . "Ha"
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.
__LINE__: The current line number of the file.
__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
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);
The above example will output:
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
Example with inheritance
<?php
class pclass { }
class childclass extends pclass { }
$a = new childclass;
var_dump($a instanceof childclass);
var_dump($a instanceof pclass);
The above example will output:
bool(true)
bool(true)
Example with Clone
<?php
class cloneable { }
$a = new cloneable;
$b = clone $a;
var_dump($a instanceof cloneable);
var_dump($b instanceof cloneable);
The above example will output:
bool(true)
bool(true)
An overview of operators in PHP:
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.
$a ? $b : $c : if $a return $b else return $c (ternary operator)
$a ?? $c : Same as $a ? $a : $c (null coalescing operator - requires 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
$a ??= $b : The value of $b is assigned to $a if $a is null or not defined (null coalescing assignment operator - requires PHP>=7.4)
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 a way known from languages like C, Java or JavaScript.
Spaceship Operator <=> (Added in PHP 7)
Examples for <=> Spaceship operator (PHP 7, Source: PHP Manual):
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
// Comparison is case-sensitive
echo "B" <=> "a"; // -1
echo "a" <=> "aa"; // -1
echo "zz" <=> "aa"; // 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
$a = (object) ["a" => "b"];
$b = (object) ["a" => "c"];
echo $a <=> $b; // -1
$a = (object) ["a" => "c"];
$b = (object) ["a" => "b"];
echo $a <=> $b; // 1
// only values are compared
$a = (object) ["a" => "b"];
$b = (object) ["b" => "b"];
echo $a <=> $b; // 1
{} Curly braces
Blocks - curly braces/no curly braces?
Curly braces in string in PHP
PHP curly braces in array notation
And some words about last post
$x[4] = 'd'; // it works
$x{4} = 'd'; // it works
$echo $x[4]; // it works
$echo $x{4}; // it works
$x[] = 'e'; // it works
$x{} = 'e'; // does not work
$x = [1, 2]; // it works
$x = {1, 2}; // does not work
echo "${x[4]}"; // it works
echo "${x{4}}"; // does not work
echo "{$x[4]}"; // it works
echo "{$x{4}}"; // it works
Null coalescing operator (??)
This operator has been added in PHP 7.0 for the common case of needing to use a ternary operator in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>
PHP Strings:
PHP Strings can be specified in four ways not just two ways:
1) Single Quote Strings:
$string = 'This is my string'; // print This is my string
2) Double Quote Strings:
$str = 'string';
$string = "This is my $str"; // print This is my string
3) Heredoc:
$string = <<<EOD
This is my string
EOD; // print This is my string
4) Nowdoc (since PHP 5.3.0):
$string = <<<'END_OF_STRING'
This is my string
END_OF_STRING; // print This is my string
QUESTION:
What does => mean?
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:
$myArray1 = array(2016, "hello", 33);//option 1
$myArray2 = [2016, "hello", 33];//option 2
$myArray3 = [];//option 3
$myArray3[] = 2016;
$myArray3[] = "hello";
$myArray3[] = 33;
Where as, if we wanted to call the array in some later part of the code, we could do:
echo $myArray1[1];// output: hello
echo $myArray2[1];// output: hello
echo $myArray3[1];// output: hello
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).
Differences (between a sequential and associative array):
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:
echo $myArray1["Greetings"];// output: hello
echo $myArray2["Greetings"];// output: hello
echo $myArray3["Greetings"];// output: hello
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:
What does "&" mean here in PHP?
PHP "&" operator
Makes life more easier once we get used to it..(check example below carefully)
& usually checks bits that are set in both $a and $b are set.
have you even noticed how these calls works?
error_reporting(E_ERROR | E_WARNING | E_PARSE);
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
error_reporting(E_ALL & ~E_NOTICE);
error_reporting(E_ALL);
So behind all above is game of bitwise operator and bits.
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.
Example That you 'll love
<?php
class Config {
// our constants must be 1,2,4,8,16,32,64 ....so on
const TYPE_CAT=1;
const TYPE_DOG=2;
const TYPE_LION=4;
const TYPE_RAT=8;
const TYPE_BIRD=16;
const TYPE_ALL=31;
private $config;
public function __construct($config){
$this->config=$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";
}
private function is($value){
return $this->config & $value;
}
}
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
== is used for check equality without considering variable data-type
=== is used for check equality for both the variable value and data-type
Example
$a = 5
if ($a == 5) - will evaluate to true
if ($a == '5') - will evaluate to true, because while comparing this both value PHP internally convert that string value into integer and then compare both values
if ($a === 5) - will evaluate to true
if ($a === '5') - will evaluate to false, because value is 5, but this value 5 is not an integer.
Null Coalesce operator "??" (Added in PHP 7)
Not the catchiest name for an operator, but PHP 7 brings in the rather handy null coalesce so I thought I'd share an example.
In PHP 5, we already have a ternary operator, which tests a value, and then returns the second element if that returns true and the third if it doesn't:
echo $count ? $count : 10; // outputs 10
There is also a shorthand for that which allows you to skip the second element if it's the same as the first one: echo $count ?: 10; // also outputs 10
In PHP 7 we additionally get the ?? operator which rather than indicating extreme confusion which is how I would usually use two question marks together instead allows us to chain together a string of values. Reading from left to right, the first value which exists and is not null is the value that will be returned.
// $a is not set
$b = 16;
echo $a ?? 2; // outputs 2
echo $a ?? $b ?? 7; // outputs 16
This construct is useful for giving priority to one or more values coming perhaps from user input or existing configuration, and safely falling back on a given default if that configuration is missing. It's kind of a small feature but it's one that I know I'll be using as soon as my applications upgrade to PHP 7.
Nullable return type declaration
PHP 7 adds support for return type declarations. Similarly to argument type declarations, return type declarations specify the type of value that will be returned from a function. The same types are available for return type declarations as are available for argument type declarations.
Strict typing also has an effect on return type declarations. In the default weak mode, returned values will be coerced to the correct type if they are not already of that type. In strong mode, the returned value must be of the correct type, otherwise, a TypeError will be thrown.
As of PHP 7.1.0, return values can be marked as nullable by prefixing the type name with a question mark (?). This signifies that the function returns either the specified type or NULL.
<?php
function get_item(): ?string {
if (isset($_GET['item'])) {
return $_GET['item'];
} else {
return null;
}
}
?>
Source
?-> NullSafe Operator
Added in PHP 8.0
It's the NullSafe Operator, it returns null in case you try to invoke functions or get values from null. Nullsafe operator can be chained and can be used both on the methods and properties.
$objDrive = null;
$drive = $objDrive?->func?->getDriver()?->value; //return null
$drive = $objDrive->func->getDriver()->value; // Error: Trying to get property 'func' of non-object
Nullsafe operator doesn't work with array keys:
$drive['admin']?->getDriver()?->value //Warning: Trying to access array offset on value of type null
$drive = [];
$drive['admin']?->getAddress()?->value //Warning: Undefined array key "admin"
Three DOTS as Splat Operator (...) (since PHP 5.6)
PHP has an operator "..." (Three dots) which is referred as Splat Operator. It is used to pass arbitrary number of parameters in a function and this type of function is called Variadic Functions. Let’s take examples to use of "..." (Three dots).
Example 1:
<?php
function calculateNumbers(...$params){
$total = 0;
foreach($params as $v){
$total = $total + $v;
}
return $total;
}
echo calculateNumbers(10, 20, 30, 40, 50);
//Output 150
?>
Each arguments of calculateNumbers() function pass through $params as an array when use "… ".
There are many different ways to use "… " operator. Below some examples:
Example 2:
<?php
function calculateNumbers($no1, $no2, $no3, $no4, $no5){
$total = $no1 + $no2 + $no3 + $no4 + $no5;
return $total;
}
$numbers = array(10, 20, 30, 40, 50);
echo calculateNumbers(...$numbers);
//Output 150
?>
Example 3:
<?php
function calculateNumbers(...$params){
$total = 0;
foreach($params as $v){
$total = $total + $v;
}
return $total;
}
$no1 = 70;
$numbers = array(10, 20, 30, 40, 50);
echo calculateNumbers($no1, ...$numbers);
//Output 220
?>
Example 4:
<?php
function calculateNumbers(...$params){
$total = 0;
foreach($params as $v){
$total = $total + $v;
}
return $total;
}
$numbers1 = array(10, 20, 30, 40, 50);
$numbers2 = array(100, 200, 300, 400, 500);
echo calculateNumbers(...$numbers1, ...$numbers2);
//Output 1650
?>
It should be noted that Variadic Parameters cannot be targeted by named arguments.
Example 5:
<?php
function sumIntegers(int ...$params): int {
$sum = 0;
foreach($params as $value){
$sum += $value;
}
return $sum;
}
echo sumIntegers(params: [1, 2, 3, 4]);
// $params will be equal to ['params' => [1, 2, 3, 4]] in sumIntegers
// throws TypeError sumIntegers(): Argument #1 must be of type int, array given
echo sumIntegers(arbitrary_name: 1, another_name: 2);
// $params will be equal to ['arbitrary_name' => 1, 'another_name' => 2] in sumIntegers
// Outputs: 3
?>
Using an unpacked associative array as the parameter for a function call has the same effect as calling the function using each key-value pair as a named argument.
Example 6:
<?php
function fullName(string $first_name, ?string $middle_name = null, ?string $last_name = null): string {
return trim("$first_name|$middle_name|$last_name");
}
$params = ['first_name' => 'John', 'last_name' => 'Doe'];
echo fullName(...$params);
// same as fullName(first_name: 'John', last_name: 'Doe')
// outputs 'John||Doe'
?>
This can be used to pass named arguments to something like a nested function call or a class.
Example 7:
<?php
function throw_exception(string $exception, ...$parameters) {
throw new $exception(...$parameters);
}
throw_exception(exception: 'Exception', code: 123);
// executes throw new Exception(...['code' => 123])
// which is the same as throw new Exception(code: 123);
?>
NullSafe Operator "?->" since php8
In PHP8 it's been accepted this new operator, you can find the documentation here. ?-> it's the NullSafe Operator, it returns null in case you try to invoke functions or get values from null...
Examples:
<?php
$obj = null;
$obj = $obj?->attr; //return null
$obj = ?->funct(); // return null
$obj = $objDrive->attr; // Error: Trying to get property 'attr' of non-object
?>
#[] attributes since PHP 8
You can write #[attribute_name] since PHP 8. This is an attribute in PHP (also Rust and C#). Other languages may use names like annotations (Java) or decorators (Python, Javascript) for a similar feature. Prior to PHP 8, #[whatever] would have been a comment until the end of the line (because # starts a comment in PHP). So if an attribute is the last thing on a line, it will be ignored in versions before PHP 8. If not the last thing on a line, it would comment out whatever was after it prior to PHP 8 (since then the ] terminates it).
RFC
Syntax RFC (the syntax was changed from the original RFC)
Documentation
In php 8
Instead of writing the classic !== null you can use the ? operator to write just 1 line of code, the code becomes pretty clear:
Before:
$firsName = null;
if ($session !== null) {
$user = $session->user;
if ($user !== null) {
$name = $user->getName();
if ($name !== null) {
$firstName = $name->firstName;
}
}
}
After:
$firsName = $session?->user?->getName()?->firstName;
Use match instead of switch. The match expression uses strict comparison (===) instead. The comparison is strict regardless of strict_types.
Before:
switch ('A') {
case 'A':
echo "found A";
break;
case 'B':
echo "found B";
break;
}
// Result: "found A"
After:
echo match ('A') {
'A' => "found A",
'B' => "found B",
};
// Result: "found A"
Double-dot syntax
When used between two characters in qualifying native PHP string functions, .. acts to express an inclusive range of characters. a-e is equivalent to abcde.
echo trim('adobe', 'a..e');
Prints:
o
Native PHP functions that allow double-dot range syntax
What does \ (backslash) symbol in PHP
It uses for to escape string type or to change specific case:
Examples:
Here \r\n and \n using for pass to new line (like enter button)
echo "Hello world \n\r I am Herakl";
Alternatively, you can use PHP_EOL. There are some exceptions. Firstly, it can use only in two quotes (") condition. Also, it is escape self
echo " Hello \\ I am robot";
In stackoverflow it doesn't see correctly.
Backslashes also use in namespaces or use condition names:
namespace App\Http\Controllers;
use App\Models;
Additionally, you should visit about slashes https://www.php.net/manual/en/function.addslashes.php

How does <=> in php 7 responsed in situations that check bool values?

Looking into php 7 on the way, but <=> confuses me.
Most of the time I use conditional operators, they are used in boolean situations (which <=> almost is, but not quite, being able to return -1 as well). (If X <=> Y). So I'm not sure what will happen in the following cases...
if ($x <=> $y) {
// Do all the 1 things
} else {
// Do all the 2 things
}
What can I expect if it's preceded by...
$x = 0; $y = 1;
or
$x = "Carrot"; $y = "Carrot Juice";
or
$x = "Carrot Juice"; $y = "Carrot";
or
$x = array(carrot, juice); $y = "carrot juice";
There's definitely enough cases about this that it's confusing me as to what it'll do.
The spaceship operator (and other PHP 7 additions) is explained in plain language here:
https://blog.engineyard.com/2015/what-to-expect-php-7
It's mostly useful in the comparison function supplied to functions like usort.
// Pre PHP 7
function order_func($a, $b) {
return ($a < $b) ? -1 : (($a > $b) ? 1 : 0);
}
// Post PHP 7
function order_func($a, $b) {
return $a <=> $b;
}
It's not very useful in if, because if only checks whether the value is truthy or falsey, the different truthy values representing the ordering are not distinguished. If you do use it in a boolean context, it will be considered true when the values are different (because 1 and -1 are bother truthy), false when they're equal (because 0 is falsey). This is similar to trying to use strcmp() and stricmp() in a boolean context, which is why you often see
if (stricmp($x, $y) == 0)
The rules for using arrays with comparison operators is given here (scroll down to the table labeled Comparison with Various Types). When comparing an array with another array, the rule is:
Array with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are uncomparable, otherwise - compare value by value
When comparing an array with another type, the array is always greater. So array('carrot', 'juice') <=> 'carrot juice' will be 1.
Why not just try it out for yourself and play around with that new spaceship you got?
Demo
Also if you are wondering how the comparison of the spaceship operator works, see: http://php.net/manual/en/types.comparisons.php
But now if we want to go into a bit more detail about your test data:
First case:
//Test data
$x = 0;
$y = 1;
//operator
0 <=> 1 //0 is smaller than 1, so result: -1
//-1 evaluates to TRUE in the if statement
Second case:
//Test data
$x = "Carrot";
$y = "Carrot Juice";
//operator
"Carrot" <=> "Carrot Juice" //"Carrot" is smaller than "Carrot Juice", so result: -1
//-1 evaluates to TRUE in the if statement
Third case:
//Test data
$x = "Carrot Juice";
$y = "Carrot";
//operator
"Carrot Juice" <=> "Carrot" //"Carrot Juice" is bigger than "Carrot", so result: 1
//1 evaluates to TRUE in the if statement
Fourth case:
//Test data
$x = array("carrot", "juice");
$y = "carrot juice";
//operator
array("carrot", "juice") <=> "carrot juice" //array("carrot", "juice") is bigger than "carrot juice", so result: 1
//1 evaluates to TRUE in the if statement
Introduction
The spaceship operator <=> is a non-associative binary operator with the same precedence as equality operators (==, !=, ===, !==).
The purpost of this operator, is to allow for simpler three-way comparison between left-hand and right-hand operands.
Possible outcomes
The operator can produce any of the following results :
0 : when both operands are equal
-1 : when the left-hand operand is less than the right-hand operand
1 : when the left-hand operand is greater than the right-hand operand.
So, that means :
1 <=> 1; // output : 0
1 <=> 2; // output : -1
2 <=> 1; // output : 1
Practical application
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.
Before PHP 7, you would write this :
$arr = [4,2,1,3];
usort($arr, function ($a, $b) {
if ($a < $b) {
return -1;
} elseif ($a > $b) {
return 1;
} else {
return 0;
}
});
Since PHP 7, you can write this :
$arr = [4,2,1,3];
usort($arr, function ($a, $b) {
return $a <=> $b;
});

Categories