PHP & Ampersand: Passing by Reference

The following PHP Reference excerpt is from pages 20-21.

& – Pass by Reference

References allow two variables to refer to the same content. In other words, a variable points to its content (rather than becoming that content). Passing by reference allows two variables to point to the same content under different names. The ampersand ( & ) is placed before the variable to be referenced.

Examples:

$a = 1;
$b = &$a; // $b references the same value as $a, currently 1
$b = $b + 1; // 1 is added to $b, which effects $a the same way
echo "b is equal to $b, and a is equal to $a";
b is equal to 2, and a is equal to 2



Use this for functions when you wish to simply alter the original variable and return it again to the same variable name with its new value assigned.

function add(&$var){ // The & is before the argument $var
$var++;
}
$a = 1;
$b = 10;
add($a);
echo "a is $a,";
add($b);
echo " a is $a, and b is $b"; // Note: $a and $b are NOT referenced
a is 2, a is 2, and b is 11

You can also do this to alter an array with foreach:

$array = array(1,2,3,4);
foreach ($array as &$value){
$value = $value + 10;
}
unset ($value); // Must be included, $value remains after foreach loop
print_r($array);
Array ( [0] => 11 [1] => 12 [2] => 13 [3] => 14 )


What tricks do you have for using the ampersand in PHP to pass by reference?
Leave them in the comments below!

Equal Sign in PHP: Equality and Not Equals

The PHP equal sign can be used to assign the value of variable as well as evaluate a variable as part of an if-else statement or other conditional statement. However, there are subtle differences that are important for ensuring your PHP code is as accurate as possible. The following samples are from page 22.

The Equal Sign

Assignment ( = ): Assigns the value on the right to the variable on the left
Equality ( == ): Checks if the left and right values are equal
Identical ( === ): Checks if the left and right values are equal AND identical (same variable type)

Example:

$a = 1; // Sets the value of $a as the integer 1
$b = TRUE; // Sets the value of $b to the boolean TRUE
if ($a == $b){
echo 'a is equal to b.';
}
if ($a === $b){ // compare VALUE and data type: if $a(integer) === $b(boolean)
echo 'a is identical and equal to b.';
}
a is equal to b. 

Not ( ! ), Not Equal to ( != ), Not Identical to ( !== )

Used in conditional statements to evaluate as true a FALSE result of an expression or if a value is NOT equal to the second value.

Example:

$a = 1;
if (!isset($a)){ // If the variable $a is NOT set then...
echo '$a is not set'; // The expression is TRUE if it is NOT set
// Since there is no ELSE statement, nothing is displayed
}
if ($a != 0){
echo '$a does not equal zero';
}
$a does not equal zero

Regular Expression Syntax (RegEx) Sample

The handy Regular Expression Syntax from the PHP book (pages 149-150). Check out the free PDF if you don’t have it already!

Regular Expression Syntax

^ – Start of string
$ – End of string
. – Any single character
( ) – Group of expressions
[] – Item range ( e.g. [afg] means a, f, or g )
[^] – Items not in range ( e.g. [^cde] means not c, d, or e )
– (dash) – character range within an item range ( e.g. [a-z] means a through z )
| (pipe) – Logical or ( e.g. (a|b) means a or b )
? – Zero or one of preceding character/item range
* – Zero or more of preceding character/item range
+ – One or more of preceding character/item range
{integer} – Exactly integer of preceding character/item range ( e.g. a{2} )
{integer,} – Integer or more of preceding character/item range ( e.g. a{2,} )
{integer,integer} – From integer to integer (e.g. a{2,4} means 2 to four of a )
\ – Escape character
[:punct:] – Any punctuation
[:space:] – Any space character
[:blank:] – Any space or tab
[:digit:] – Any digit: 0 through 9
[:alpha:] – All letters: a-z and A-Z
[:alnum:] – All digits and letters: 0-9, a-z, and A-Z
[:xdigit:] – Hexadecimal digit
[:print:] – Any printable character
[:upper:] – All uppercase letters: A-Z
[:lower:] – All lowercase letters: a-z

PERL Compatible (PCRE) only ( preg_*() )

/ – delimiter before and after the expression

Character classes:

\c – Control character
\s – Whitespace
\S – Not whitespace
\d – Digit (0-9)
\D – Not a digit
\w – Letter, Digit, Underscore [a-zA-Z0-9_]
\W – Not a letter
\x – Hexadecimal digit
\O – Octal digit

Modifiers:

i – Case-insensitive
s – Period matches newline
m – ^ and $ match lines
U – Ungreedy matching
e – Evaluate replacement
x – Pattern over several lines

Sprintf() Function Sample

sprintf(formatting, inputs [, …inputs…]

Accepts multiple inputs to be used when specified in formatting

formatting$string, specific formatting string, explained below
inputs $scalar(s) to be formatted

Returns a formatted string formatting, using the inputs to dynamically input their values into the formatted string using a preset set of rules, specified below.

The following is the available nomenclature for the formatting input.


Every time an input is expected to be used and evaluated as part of the formatted string, it is preceded by a percent sign ( % ), followed by the specifiers/rules:
Note: All specifiers, excluding the type specifier, are optional.

  • A sign specifier. Placing a plus sign ( + ) forces negative AND positive signs to be visible (only negative values are specified by default).

  • A padding specifier. The default is a space, and does not need to be specified. A zero ( 0 ) can be used as well without any secondary notation. If any other character is to be used, it should be preceded with a single quote ( ‘ ).

  • An alignment specifier. The default is right-justified (thus padding is placed on the left of the string). Placing a dash/subtract ( – ) will set it to left-justified.

  • A width specifier. This integer determines the minimum length in characters the output should be. When combined with padding, the specified width minus the input’s length determines the number of padded characters that will be added.

  • A precision specifier. A period ( . ) followed by an integer, sets the number of decimal places that should be output for a float. If used on a string, it sets a maximum character limit for the output.

  • A type specifier:

    • % – a literal percent sign, thus would be written %% to display a percent sign in the formatting string

    • b – the input should be an integer, a binary number is the output.

    • c – the input should be an integer between 0-255, representing the ASCII byte-value. The character represented is output.

    • d – the input should be an integer.

    • e – the input is scientific notation.

    • u – the input is an unsigned decimal number.

    • f – the input is a float (locale aware).

    • F – the input is a float (not locale aware).

    • o – the input is an integer, an octal number is the output.

    • s – the input is a string.

    • x – the input is an integer, a hexadecimal number is the output (with lowercase letters).

    • X – the input is an integer, a hexadecimal number is the output (with uppercase letters).

Examples:

Basic substitution, no optional specifiers

$string = ‘cat’;
$integer = 10;
echo sprintf(“I have %d %s(s)”, $integer, $string);

I have 10 cat(s)

Basic substitution, type specification automatic adjustments

$string = ‘cat’;
$string2 = ’10 blah’;
echo sprintf(“I have %d %s(s)”, $string2, $string);

I have 10 cat(s)

Using the sign specifier

$string = ‘cat’;
$integer = ’10’;
echo sprintf(“Dagger has a %+d against %ss”, $integer, $string);

Dagger has a +10 against cats

Using padding and width specifiers (default padding specifier of a space)

$string = ‘cat’; // length, 3 characters
echo ‘

’; // HTML Required to display the formating properly
echo sprintf(“3 spaces added: |%6s”, $string);
// Used padding of 6 characters, 6 – 3 = 3 spaces padded

Pad from line 3 spaces: |   cat

Using padding and width using a zero ( 0 ) for padding

$month = 12;
$day = 1;
$year = 1980;
echo sprintf (” Date: %02d/%02d/%04d.”, $month, $day, $year);
$year = 80;
echo sprintf (” Date: %02d/%02d/%04d.”, $month, $day, $year);

Date: 12/01/1980. Date: 12/01/0080.

Using padding and width using a custom character, the asterisk ( * )

$endofpassword = ‘word’;
$output = sprintf(“Your password: %’*8s”, $endofpassword);
echo $output;

Your password: ****word

Using padding, alignment (left), and width

$endofpassword = ‘word’;
$output = sprintf(“Your password: %’*-8s”, $endofpassword);
echo $output;

Your password: word****

Using the precision specifier

$scientific = 1.2e3;
echo sprintf(“Three decimal places: %.3e”, $scientific);

Three decimal places: 1.200e+3

$float = 1.2e3;
echo sprintf(“Two decimal places: %.2f”, $float);

Two decimal places: 1200.00

$string = ‘Hello World!’;
echo sprintf(“Cut-off after 4 characters: %.4s”, $string);

Cut-off after 4 characters: Hell

See Also:

printf() – prints a formatted string results rather than simply returning them
sscanf() – Parses a string through a formatted string, reverse of sprintf()