PHP – Passing Variables By Reference and By Value

May 19th, 2010

By default in PHP, variables are passed around ‘by value’. i.e.

<?php
function increment($i)
{
$i++;
return $i;
}

$a = 10;
$b = increment($a);
?>

At this point, $a remains as 10, however $b is now 11. $b = increment(10); works just the same, and you can assign 10 back to the original variable with: $a = 10; $a = increment($a); This is called passing variables by value. i.e. I am passing the VALUE of $a to the increment() function.

We also have the option of passing variables by reference. For programmers that have worked with C before, this is a ‘pointer’.

<?php
function increment(&$i)
{
$i++;
return $i;
}

$a = 10;
increment($a);
echo “a has now become: ” . $a;
?>

In the case above, I am passing $a by reference.  i.e. the increment() function is operating on the variable $a rather than the value of the variable. Certain things that shouldn’t work get fixed by PHP, i.e. increment(&$a). By the time the increment() function gets to it, it is actually passing the reference to the reference to the variable. Certain other things will fail entirely, i.e. increment(10); will give “Fatal error: Only variables can be passed by reference”

PHP Programmer – Remove characters from the end of a string

May 18th, 2010

<?php
$s = “This is my string”;
$s = substr($s, 0, strlen($s)-2);
?>

This trims 2 characters from $s, resulting in “This is my stri”;

PHP – Checking for Array Keys

May 14th, 2010

As a PHP Programmer, I recently came up against an error while testing another developer’s code.. Within PHP, testing for the existance of the referring URL:

if (empty($_SERVER[‘HTTP_REFERER’])) will produce a notice:
Undefined index: HTTP_REFERER

The correct way to check for the existence of an array key is: if (array_key_exists(“HTTP_REFERER”, $_SERVER))