PHP "&" Operator

php using '&' operator

function &foo() {}

Returns a variable by reference from calling foo().

function foo($id, &$desc) {}

Takes a value as the first parameter $id and a reference as the second parameter $desc. If $desc is modified within the function, the variable as passed by the calling code also gets modified.

The first two questions are answered by me in greater detail with clearer examples here.

And this:

foreach ($data as $key => &$item) {}

Uses foreach to modify an array's values by reference. The reference points to the values within the array, so when you change them, you change the array as well. If you don't need to know about the key within your loop, you can also leave out $key =>.

How does the & operator work in a PHP function?

The & operator tells PHP not to copy the array when passing it to the function. Instead, a reference to the array is passed into the function, thus the function modifies the original array instead of a copy.

Just look at this minimal example:

<?php
function foo($a) { $a++; }
function bar(&$a) { $a++; }

$x = 1;
foo($x);
echo "$x\n";
bar($x);
echo "$x\n";
?>

Here, the output is:

1
2

– the call to foo didn’t modify $x. The call to bar, on the other hand, did.

PHP &$string - What does this mean?

You are assigning that array value by reference.

passing argument through reference (&$) and by $ is that when you pass argument through reference you work on original variable, means if you change it inside your function it's going to be changed outside of it as well, if you pass argument as a copy, function creates copy instance of this variable, and work on this copy, so if you change it in the function it won't be changed outside of it

Ref: http://www.php.net/manual/en/language.references.pass.php

Why do I have to use the reference operator (&) in a function call?

From the PHP docs

Note: Unlike parameter passing, here you have to use & in both places - to indicate that you want to return by reference, not a copy, and to indicate that reference binding, rather than usual assignment, should be done for $myValue.

http://php.net/manual/en/language.references.return.php

Basically, its to help the php interpreter. The first use in the function definition is to return the reference, and the second is to bind by reference instead of value to the assignment.

By putting the & in the function declaration, the function will return a memory address of the return value. The assignment, when getting this memory address would interpret the value as an int unless explicitly told otherwise, this is why the second & is needed for the assignment operator.

EDIT: As pointed out by @ringø below, it does not return a memory address, but rather an object that will be treated like a copy (technically copy-on-write).

What does a single ampersand mean in a PHP conditional statement?

That is a bitwise AND operation: http://www.php.net/manual/en/language.operators.bitwise.php

If, after the bitwise AND, the result is "truthy", the clause will be satisfied.

For example:

3 & 2 == 2 // because, in base 2, 3 is 011 and 2 is 010
4 & 1 == 0 // because, in base 2, 4 is 100 and 1 is 001

This is commonly used to check a single bit in a bitset, by testing powers of two, you are actually checking if a specific bit is set.

Reference — What does this symbol mean 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

Difference between & and && in PHP

& is bitwise AND. See Bitwise Operators. Assuming you do 14 & 7:

    14 = 1110
7 = 0111
---------
14 & 7 = 0110 = 6

&& is logical AND. See Logical Operators. Consider this truth table:

 $a     $b     $a && $b
false false false
false true false
true false false
true true true

Can you pass by reference while using the ternary operator?

Simple answer: no. You'll have to take the long way around with if/else. It would also be rare and possibly confusing to have a reference one time, and a value the next. I would find this more intuitive, but then again I don't know your code of course:

if(!isset($_SESSION['foo'])) $_SESSION['foo'] = false;
$x = &$_SESSION['foo'];

As to why: no idea, probably it has to with at which point the parser considers something to be an copy of value or creation of a reference, which in this way cannot be determined at the point of parsing.

How do I check if a string contains a specific word?

Now with PHP 8 you can do this using str_contains:

if (str_contains('How are you', 'are')) { 
echo 'true';
}

RFC

Before PHP 8

You can use the strpos() function which is used to find the occurrence of one string inside another one:

$haystack = 'How are you?';
$needle = 'are';

if (strpos($haystack, $needle) !== false) {
echo 'true';
}

Note that the use of !== false is deliberate (neither != false nor === true will return the desired result); strpos() returns either the offset at which the needle string begins in the haystack string, or the boolean false if the needle isn't found. Since 0 is a valid offset and 0 is "falsey", we can't use simpler constructs like !strpos($a, 'are').



Related Topics



Leave a reply



Submit