Re: Arrays : returning a reference to an array item ??

From: Michael Fesser (netizen_at_gmx.net)
Date: 08/12/04


Date: Thu, 12 Aug 2004 01:32:19 +0100


 .oO(Nico)

>The point is : return a reference to the array's item (foo), to do whatever
>with the data included therein...
>Is it clearer this way ?

<?php
function &searchItem(&$itemList, $name) {
  foreach($itemList as $key => $item) {
    if ($item['name'] == $name) {
      return $itemList[$key];
    }
  }
  return NULL;
}

$foo = array(
  array('name' => 'apple', 'color' => 'green'),
  array('name' => 'lemon', 'color' => 'yellow')
);

header('Content-type: text/plain');
print_r($foo);
$bar = &searchItem($foo, 'lemon');
$bar['color'] = 'blue';
print_r($foo);
?>

Notice the used '&':
1) The argument $itemList is passed by reference.
2) The search function returns a reference.
3) Assigning the return value to a variable also needs a reference
   operator.

HTH
Micha



Relevant Pages

  • possible bug with recursive array references
    ... I am using PHP 5.0.4 with Apache 2, ... creates the reference when it is being assigned to an array element ... existing reference and avoids the problem. ... The only difference is the reference assignment at the beginning of the ...
    (comp.lang.php)
  • Re: Inheritance of constructors.
    ... Bare in mind that was just for sake of example. ... In case of "reference by value" that's not ... Foo foo = new Foo; ... The changes to the array are visible in Foo, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Passing $_REQUEST by reference - sensible thing to do?
    ... I come a bit from the old school of programming trying to save as much CPU time as possible and I have made the assumption that if I'm calling a method of one of my classes that I want to do work on the $_REQUEST variables, ... rather then pass the object to my class method, instead I pass it by reference. ... Array created: 76,546,048 bytes ... the easiest way to make your PHP app slow is having an awful database design. ...
    (comp.lang.php)
  • Re: PHP object references and iterating through an array
    ... retrieving a to each object in the array, ... method on the array. ... that I return the object by REFERENCE rather than by VALUE? ... Are you using PHP 4? ...
    (comp.lang.php)
  • Re: Passing $_REQUEST by reference - sensible thing to do?
    ... $foo = strlen; ... PHP is passing by reference under the covers in both cases. ... You will find the pass by reference is significantly faster - and the larger the original string, ...
    (comp.lang.php)