Reference — What does this symbol mean in PHP?

Created 17.09.2010 16:24
Viewed 721K times
4716 votes

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 to the help others provided.

The List

If your particular token is not listed below, you might find it in the List of Parser Tokens.


& Bitwise Operators or References


=& References


&= Bitwise Operators


&& Logical Operators


% Arithmetic Operators


!! Logical Operators


@ Error Control Operators


?: Ternary Operator


?? Null Coalesce Operator (since PHP 7)


?string ?int ?array ?bool ?float Nullable return type declaration (since PHP 7.1)


: Alternative syntax for control structures, Ternary Operator, Return Type Declaration


:: Scope Resolution Operator


\ Namespaces


-> Classes And Objects


=> Arrays


^ Bitwise Operators


>> Bitwise Operators


<< Bitwise Operators


<<< Heredoc or Nowdoc


= Assignment Operators


== Comparison Operators


=== Comparison Operators


!== Comparison Operators


!= Comparison Operators


<> Comparison Operators


<=> Comparison Operators (since PHP 7.0)


| Bitwise Operators


|| Logical Operators


~ Bitwise Operators


+ Arithmetic Operators, Array Operators


+= and -= Assignment Operators


++ and -- Incrementing/Decrementing Operators


.= Assignment Operators


. String Operators


, Function Arguments

, Variable Declarations


$$ Variable Variables


` Execution Operator


<?= Short Open Tags


[] Arrays (short syntax since PHP 5.4)


<? Opening and Closing tags


... Argument unpacking (since PHP 5.6)


** Exponentiation (since PHP 5.6)


# One-line shell-style comment


?-> NullSafe Operator Calls (since PHP 8.0)


17
Comments
I know this isn't strictly PHP, but what about including a link to phpdoc.org for phpDocumentor comment syntax, which is commonly used and it's also impossible to search for /**? by Mike, 21.08.2011 02:25
Can I suggest square bracket and curly bracket ? by ajreal, 26.11.2011 10:38
I ran into this problem a lot too (not being able to search for special characters), which is why I made SymbolHound, a search engine that doesn't ignore special characters. I also posted it on StackApps. by dncrane, 06.12.2011 18:34
Well, from the heading Why is this?, I'd guess it's because "The main idea is to have links to existing questions on Stack Overflow, so it's easier for us to reference them". by Herbert, 26.08.2012 18:34
Amazing post. Even as an senior php developer this is very handy to reference at times when I need to verbally explain things to my team. by Josh, 26.08.2014 16:21
Should we add this one? It's not syntax, but similarly hard to google, and may look like syntax to some people. by Martin Ender, 05.11.2014 14:50
A question was asked today (Nov.20/15) stackoverflow.com/questions/33833259/what-is-rscat-in-php asking "What is $rsCat in php" (should that question still be made visible and not deleted). Strangely enough, there isn't a reference about $ variable, but about $$ Variable Variables only. I believe that should be amended somewhere. by Funk Forty Niner, 20.11.2015 18:19
I came across this one the other day: |= by Typel, 04.12.2015 22:48
@Typeless did you mean stackoverflow.com/questions/3362626/…? by Gordon, 06.12.2015 15:08
@Gordon. No, I actually saw it in a popular PasswordHash class. The full line looks like this: $diff |= ord($a[$i]) ^ ord($b[$i]); by Typel, 08.12.2015 17:24
@davejal: Please make sure a tag applies instead of simply blindly adding it. by Deduplicator, 15.01.2016 23:19
@dncrane - I could not search for ... javascript (spread/rest) rainsoft.io/how-three-dots-changed-javascript by mplungjan, 01.09.2017 12:02
@Gordon I recently closed this question and wanted to use this Q&A to close it with, however the ? query string character isn't included here. I closed the question with two other ones instead that directly address it. Do you feel that it should be added in this Q&A here? by Funk Forty Niner, 17.09.2017 22:52
@Gordon The "... Argument unpacking (since PHP 5.6)" hyperlink for wiki.php.net/rfc/argument_unpacking produces as "502 Bad Gateway" for me today on a few browsers. You may want to look into that and am unsure if you saw my previous comment just above this one a few days prior. I saw this question today and was going to close the question with this one, but cannot since the link isn't valid right now. by Funk Forty Niner, 20.09.2017 12:22
@Fred-ii- 1. Let's stick to PHP syntax only, ? in a URL is unrelated. 2. This is a community wiki, edit/add as needed. by deceze, 20.09.2017 12:28
@deceze Oh I see. Ok well, if it's unrelated then it (I) shouldn't add to it then, correct? Edit: I see you fixed the reference for the ... link. by Funk Forty Niner, 20.09.2017 12:30
Here's the names of all the PHP operators (TOKEN). Reference php.net/manual/en/tokens.php ![enter image description here](i.stack.imgur.com/P5ilY.jpg) by Mahmoud Zalt, 23.11.2017 00:04
Show remaining 12 comments
Answers 20
3
1225

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:

17.09.2010 16:30
Comments
For everyone's sake, please remove the bolded information about pre-incrementing being infinitesimally faster. This is the absolute worst example of premature optimization and this kind of information should not be in people's heads if they are just starting to learn PHP. by Lotus Notes, 08.12.2010 23:49
@Lotus - I consider it a fun fact. If you're a beginner to PHP, or C++, etc, it seems pretty wacky that ++i and i++ are different enough to work at different speeds. I found it fascinating. by Peter Ajtai, 09.12.2010 10:47
@Peter Ajtai Yes, it's interesting, but from the way you've structured your post you make it seem like one of the prime facts of PHP that is absolutely vital to using the language. by Lotus Notes, 09.12.2010 17:43
4
459

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.

31.10.2012 13:28
Comments
What if $a takes a value greater than 255? by Aycan Yaşıt, 28.09.2013 09:35
@AycanYaşıt Most of the operating system is using 32 bit and 64 bit system, that means the limit is much more than 255 (8 bits). by AlbertSamuel, 17.05.2016 03:42
@AycanYaşıt Actually, the representation here with one byte length isn't even correct, as even the smallest integer is still 64 bit (8 byte) in memory on a modern 64bit platform. by Kaii, 16.04.2018 21:53
Why and & is 0 0 0 0 1 0 0 0 and or | is 0 0 0 0 1 0 1 1? by Vi_real, 13.02.2019 21:47
9
321

<=> 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 -1 * ($a <=> $b); // for reversing order
});
08.07.2015 16:44
Comments
Not sure how $a <=> $b is different to $a - $b by rev, 28.08.2015 17:37
@AcidShout $a - $b works for numbers, but not strings, objects, or arrays. by mcrumley, 25.09.2015 18:29
@mcrumley No, it's worse than that. In general $a - $b doesn't even work for numbers; it works only for integers. It doesn't work for non-integer numbers, because usort casts your comparator function's return values to int, which means 0.5 gets cast to 0, which means that two numbers with a difference of less than 1, such as 4 and 4.6, may (depending upon which one gets passed as the first argument to your comparator function) incorrectly compare as equal. by Mark Amery, 05.11.2015 15:54
Sherif, why state that the operator returns "less than 0", 0 or "more than 0" rather than simply stating that it returns 1, 0, or -1? The latter is both more precise and more succinct; I don't understand why you reverted that detail of my edit. by Mark Amery, 15.01.2016 00:13
Btw, prior to PHP7 there's still a way to avoid if-else block that works not only with numbers: return $a < $b ? -1 : $a != $b; by Alma Do, 15.01.2016 13:04
@MarkAmery Because that is the documented behavior. by Sherif, 19.01.2016 21:38
@Sherif php.net/manual/en/migration70.new-features.php documents it as 1 / 0 / -1, not to mention that the original RFC did likewise. I think that's sufficient documentation to justify including the same detail here, and have rolled back for now; feel free to rollback and continue this argument if you still disagree. by Mark Amery, 20.01.2016 18:54
@MarkAmery the migration guide isn't the documented behavior of the operator. For that you want to look at the language operators section of the manual for that php.net/language.operators.comparison the actual behavior behind this relies on various comparison functions of the API, like when you're doing strcmp for strings, where you can not guarantee the actual return value in every single case. Sure, it's almost always 1, 0, or -1, but for the cases where you can't guarantee it like in wrapping libc's strcmp, you offer up the same defined behavior as the underlying spec to be safe by Sherif, 20.01.2016 22:45
@MarkAmery The point here is not to allow people to rely on undefined behavior. For the one case where someones gets a value that is not exactly 1, 0, or -1, you get someone filing a bug report thinking there's something wrong in the language. Which is why we document that all we can guarantee is that value will be less than, greater than, or equal to 0, and not necessarily 1, 0, and -1. by Sherif, 20.01.2016 22:50
Show remaining 4 comments
3
290

_ Alias for gettext()

The underscore character '_' as in _() is an alias to the gettext() function.

29.11.2012 09:07
Comments
Any idea what the double underscore function is? __(). It is used in WordPress. I cannot find a definition for it anywhere. Example of its use: core.trac.wordpress.org/browser/tags/5.4/src/wp-admin/includ‌​es/…. It seems that to use the WP image_size_names_choose() filter, __() must be used to add the "short name" to the array of named_sizes you want to add. by SherylHohman, 01.07.2020 01:54
@SherylHohman Look like it is translation function. developer.wordpress.org/reference/functions/__ by Mohammed H, 02.07.2020 03:08
Thanks so much! I envy your superior Google skills (and vast coding knowledge) :-) by SherylHohman, 03.07.2020 07:24
0
283
SyntaxNameDescription
x == yEqualitytrue if x and y have the same key/value pairs
x != yInequalitytrue if x is not equal to y
x === yIdentitytrue if x and y have the same key/value pairs
in the same order and of the same types
x !== yNon-identitytrue if x is not identical to y
++xPre-incrementIncrements x by one, then returns x
x++Post-incrementReturns x, then increments x by one
--xPre-decrementDecrements x by one, then returns x
x--Post-decrementReturns x, then decrements x by one
x and yAndtrue if both x and y are true. If x=6, y=3 then
(x < 10 and y > 1) returns true
x && yAndtrue if both x and y are true. If x=6, y=3 then
(x < 10 && y > 1) returns true
x or yOrtrue if any of x or y are true. If x=6, y=3 then
(x < 10 or y > 10) returns true
x || yOrtrue if any of x or y are true. If x=6, y=3 then
(x < 3 || y > 1) returns true
a . bConcatenationConcatenate two strings: "Hi" . "Ha"
31.10.2012 12:59
0
245

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

24.04.2013 04:43
1
156

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)
31.10.2013 05:48
Comments
The above works with 'interfaces' as well. This is useful for checking that a particular interface is available. by Ryan Vincent, 24.02.2014 11:38
1
144

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.

18.01.2016 06:13
Comments
There is an error in $a ?? $c, it says is the same as $a ? $a : $c, but ternary operator checks if value is true, on the other hand, null coalescing checks for null values, so, if $a is 0, you will get 0 (because 0 is not null), for example if you have: $a=0; $c=5; then $a?$a:$c returns 5, and $a??$c returns 0. by stramin, 29.07.2019 18:41
0
107

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
11.10.2015 14:15
1
76

{} Curly braces

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
23.11.2015 20:27
Comments
{''} notation for property names. echo $movies->movie->{'great-lines'}->line; can be used to access data in SimpleXMLElement. Maybe it can be used in other cases too. php.net/manual/en/simplexml.examples-basic.php by Andrei, 05.09.2017 12:15
0
69

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';
?>
31.10.2016 13:38
1
65

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
17.12.2015 07:41
Comments
@Rizier123 : What does mean by "Heredocs can not be used for initializing class properties. Since PHP 5.3, this limitation is valid only for heredocs containing variables."? by PHPFan, 26.11.2017 03:48
0
50

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.

12.06.2016 11:07
0
38

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
18.03.2017 06:05
0
31

== 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

  1. if ($a == 5) - will evaluate to true

  2. 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

  3. if ($a === 5) - will evaluate to true

  4. if ($a === '5') - will evaluate to false, because value is 5, but this value 5 is not an integer.

03.10.2017 13:28
0
28

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.

06.12.2017 16:05
0
13

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

16.01.2019 12:42
1
11

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

?>
30.09.2019 15:21
Comments
[TODO] Include new functionality in PHP8 to use the splat operator with "named parameters" ref: stackoverflow.com/a/64997399/2943403 by mickmackusa, 14.12.2020 01:10
7
8

?-> 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"
03.06.2020 17:20
Comments
Adding this feels rather premature, nobody will see this operator in any live code, and it might not even be added. It would be better to wait until the details are finalised and document it properly. by IMSoP, 03.06.2020 17:32
We are already getting questions on it. :/ If the proposal fails we can then decide if this is worth keeping. by John Conde, 03.06.2020 17:33
@JohnConde I'd be tempted to close them as off-topic, because they're asking about an imaginary programming language; or perhaps "this question belongs on a different part of the timeline, please check the settings on your time machine" ;) by IMSoP, 03.06.2020 17:36
lol The thought crossed my mind. I asked myself if this would offer value to future visitors and, for now, the answer is "yes". But that may change... by John Conde, 03.06.2020 17:38
@JohnConde The problem is that we can't actually give a correct answer yet - the actual behaviour of the operator might completely change, or it might never be added, so anything we write now is as likely to mislead as inform. The only honest answer is "a syntax error, but there's a possibility it will mean something in the future". by IMSoP, 03.06.2020 17:42
I can't say I disagree with your point of view. I'm okay with that as an answer. by John Conde, 03.06.2020 17:48
@JohnConde. The proposal of Nullsafe operator is accepted and implemented in PHP 8. Kindly update your answer. Also update RFC link. by Umair Khan, 21.09.2020 12:06
Show remaining 2 comments
7
8

NullSafe Operator "?->" (possibly) 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
?>
03.06.2020 17:24
Comments
Adding this feels rather premature, nobody will see this operator in any live code, and it might not even be added. It would be better to wait until the details are finalised and document it properly. by IMSoP, 03.06.2020 17:32
@IMSoP i'm with you, however i was invited to do so here stackoverflow.com/questions/62178354/… ... by Berto99, 03.06.2020 17:37
It looks like we now have two answers about this. Personally, I would just have voted to close the other question rather than trying to answer, because right now there is no such operator. by IMSoP, 03.06.2020 17:46
@IMSoP there are a lot of questions here on StackOverflow about C++ Proposal, and they are not been closed: despite that, i'm with you about not posting here this operator for the moment by Berto99, 03.06.2020 17:54
I don't know much about the C++ process and when it's reasonable to discuss proposals, and to be fair this one seems fairly likely to succeed workout modification, but in general there are a lot of features proposed for PHP that never make it to the language, and it would be rather confusing for users to come across them all in reference lists. That said, I'm partly just being a grumpy old man here :P by IMSoP, 03.06.2020 17:58
Ahah @IMSoP i'm a relative newby here, i code only in the next 6 years, so I trust you, if you tell me it's not his place, I'll take it off by Berto99, 03.06.2020 18:01
@Berto99 The proposal of Nullsafe operator is accepted and implemented in PHP 8. Kindly update your answer. Also update RFC link. by Umair Khan, 21.09.2020 12:08
Show remaining 2 comments