Code2Design.com

User login

The Layout

Programming

Graphic Design

Resources

Navigation

C2D Projects

Unsystematic Affiliates

PhotoShop Aid Adobe Tutorialz AOM Designs Tutorial Mix 

Change Language

Who's online

There are currently 0 users and 3 guests online.

Arrays by reference

I have been using lots of functions to create and check my variables and arrays lately. Along these lines, I thought I would take some time to share how the concept of "passing values by reference" works.

Basically, if you are anything like me you are always passing functions values and then having that function "return" a value. While there is nothing wrong with this approach, there is often an easier way to work with values in functions. Besides making values "global", you can also pass a function a value by reference.

Here is the standard way most people would work with a value in a function and then collect the functions return value.

<?php

////////////////////////////////
// Standard Function
////////////////////////////////

//Lets create a variable;
$my_variable '';

//Create the "add_key" function
function add_key($key) {
   
   
//Create an new array();
   
$array = array();
   
   
//Ad a key called "new_key" to the array
   
$array[$key] = 'value';
   
   
//return the $array
   
return $array;
}

//Run the function "add_key()" and place the output into 
//$my_variable turning it from an empty variable, into an array!
//In other words, $my_variable is now an array with 1 key called "new_key";
$my_variable add_key('new_key');


?>

$my_variable is now an array ready for you to use in the rest of your script. If you were to run the print_r() function right now you would see that $my_variable looks like the following to PHP.

Array
(
[new_key] => value
)

So now that we're all "on-the-same-page" so to speak, I want to show you how you can use PHP to cut out a little junk from your script. First though, we need to cover the "&" (and) character. The "&" character means that you aren't working with the variable/array/etc. - you are only working with a pointer to that variable/array/etc. In other words, if you mess with something that has a "&" in front of it you are following that $variables sign to another variables value in the computers memory and changing it!

References in PHP are a means to access the same variable content by different names... ...Note that in PHP, variable name and variable content are different, so the same content can have different names. - php.net

If you are lost look at this:

<?php

$foo 
'Hello';
$bar 'World'
print 
$foo " " $bar;
//Prints "Hello World"

//Change $bar to equal "Hello My World"
$bar 'Hello My World';
//Change $foo to equal the value of a variable called "$bar"
$foo = &$bar;

print 
$foo;
//Finds the value of $bar, and Prints "Hello My World"
print $bar;
//Prints "Hello My World"

//Change $bar to equal "This is bar"
$bar 'This is bar';

print 
$foo;
//Finds the value of $bar, and Prints "This is bar"
print $bar;
//Prints "This is bar"

?>

As you can see, from now on $foo will always be eqaul to whatever $bar is equal too! This is quite a useful feature if it is used in the right way!

Taking our first block of code lets change it to use this new type of "variable reference" thinking.

<?php

////////////////////////////////
// Simple Function Reference
////////////////////////////////

//Lets create a variable;
$my_variable '';

//Create the "add_key" function and set the
//value of to $array to whatever variable was given
//to the function.
function add_key2(&$array$key) {
   
   
//This now changes $my_variable into an array
   
$array = array();
   
   
//Ad a key called "new_key" to $array, which points to $my_variable
    //So add a new key to $my_variable!
   
$array[$key] = 'value';
   
   
//There is nothing to return so we don't need this.
    //return $array;
}

//Run the function "add_key2()" which works with a reference to 
//$my_variable in real time so when add_key is done running, 
//$my_variable is already updated!
add_key2($my_variable'new_key');


?>

$my_variable was transformed into an array by add_key2. Because the first part of the function had a "&" in front of the value to pass the function. That & means that whenever add_key2 worked with "$array", it was really working with "$my_variable"! If you were to run the print_r() function right now you would see that $my_variable looks like the following to PHP.

Array
(
[new_key] => value
)

So both methods accomplish the same thing just in different ways. Below is a more complex function I built for CodeXplorer that will add values to any array you tell it. You might need to download it and run it if you have trouble following the code.

<?php


////////////////////////////////
// Complex Function Reference
////////////////////////////////


///////////////////////////////////////////////////////////
// A function to set multiple array variables if they don't exist.
///////////////////////////////////////////////////////////
function create_array_keys(&$array$keys$value='') {
    foreach (
$keys as $key) {
       
//if the key is not in the array, create it!
       
if (!array_key_exists($key$array)) { 
           
$array[$key] = $value
        }
    }
   
//There is nothing to return (everything is done by reference).
}

//Create my empty array
$my_array = array();

//create an array of keys I want to add to the array
$keys = array('key_1''key_2''key_3''key_4');

//See what $my_array looks like
print '<pre>';
print_r($my_array);
print 
'</pre>';

//If the following values are not set, create them in the array "$my_array" and set them to "TRUE".
create_array_keys($my_array$keystrue);

//See what $my_array looks like now!
print '<pre>';
print_r($my_array);
print 
'</pre>';

?>

If you ran the above code you would see the following output.

<pre>
Array
(
)
</pre>
<pre>
Array
(
[key_1] => 1
[key_2] => 1
[key_3] => 1
[key_4] => 1
)
</pre>

So I hope this lesson helps you to better understand how to use PHP's powerful references to avoid having to pass variables around different functions. With references you can simply run a function and know that the variable is being updated automatically. If you want more information on this topic you can visit the PHP manual at php.net - Arguments passed by reference and php.net - References Explained.


Submitted by David on January 17, 2008 - 8:18pm.
printer friendly version

Arrays & References

Please watch the piece of code below.... I have $z as reference to $y, I change the value of $y but the value of $z is still the old one and not changed... I'm really confused, can some body help?

<?php
class foo {
   
private $list;

    function 
__construct()
    {
        for(
$i 0$i 4$i++)
           
$this->list[$i] = $i;
    }

   
public function &GetArray()
    {
        return(
$this->list);
    }
}


$x = new foo();
$y = &$x->GetArray();
$z $y// now $z is also a reference to $list, or?

$y[2] = 9// Here I change element 3's value

print_r($y); // this prints: Array ( [0] => 0 [1] => 1 [2] => 9 [3] => 3 )

print_r($z); // here is the surprizing, it does not print the same output as $y but
             // it prints: Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 )
?>

Thank you
Mizhad


Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <br> <br /> <h3>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • You can use BBCode tags in the text, URLs will be automatically converted to links
More information about formatting options



Like what you see?

Why not add more? C2D is looking for other Christian Web Masters who would like to help write articles for this site. If you have expericance in FLASH, CSS/HTML, PHP/MySQL, PhotoShop/GIMP, Blender, Javascript, or just General Design - our users would love to hear what you have to say. Contact Us

delicious   digg   reddit   magnoliacom   newsvine   furl   google   yahoo   technorati