RU beehive logo ITEC dept promo banner
ITEC 325
2012fall
ibarland

homelectsexamshws
D2Lbreeze (snow day)

lect02c-pass-by-value
looping over arrays

show-source

show-source, takes a string (filename), and prints a nice html-formatted version.

In your hw, include a show-source; I'll use that to grade your source-code. ... But we don't want to show the contents of our hw, so instead: only show-source after the hw is due: time, and strtotime.

You can find an example at: lect01b-blend-v7.php.

Looping over arrays

Looping over arrays: foreach. You can loop just over the values, or over key-value pairs.

pass-by-value

PHP uses pass-by-value, by default. Here's what that means: When calling a function: All values are written down and handed to the function; the function copies that value into its parameter/variable.

In particular, when you pass an array (or any object), a clone of that entire array is made, and passed. In fact, even when you assign one array to another, a copy is made:

$a = 5;
$b = $a;  // a *copy* of 5 is made.

$x = array(1,2,3,4);
$y = $x;     // a *copy* of array(1,2,3,4) is made.
$y[2] = 99;
echo $x[2], " ", $y[2];


function add1ToAll( $data ) {
  foreach ($data as $k => $val) {
    $data[$k] += 1;
    }
  return $data;
  }

echo "before:"
print_r($x);
add1ToAll($x);
echo "after calling but ignoring return-value:"
print_r($x);
$x = add1ToAll($x);
echo "after calling and re-assigning the return-value:"
print_r($x);

// Note that there were *three* array-copies happening  in `$x = add1ToAll($x)` --
// One to copy the parameter into the function; one copying the return value back,
// and one when assigning the return-value (back) into $x.



function add1ToAllByReference( &$data ) {
  foreach ($data as $k => $val) {
    $data[$k] += 1;
    }
  //return $data;  // no need to return a passed-by-reference var.
  }
echo "before:"
print_r($x);
add1ToAll($x);
echo "after calling but ignoring return-value:"
print_r($x);
$x = add1ToAll($x);
echo "after calling and re-assigning the return-value:"
print_r($x);

// Note that there were *three* array-copies happening  in `$x = add1ToAll($x)` --

This is different from pass-by-reference: In C, when you pass an array to a function, it actually passes a reference to the array — any changes you make to the fields are seen by the caller.

Java uses call-by-value, but object-references are one type of value. (Many people get confused by this, and think that Java passes objects by reference, but it ain't so.) That is, you can pass an int, or a boolean, or a reference-to-String, or reference-to-Puppy.

(example/pictures)

homelectsexamshws
D2Lbreeze (snow day)


©2012, Ian Barland, Radford University
Last modified 2012.Nov.28 (Wed)
Please mail any suggestions
(incl. typos, broken links)
to ibarlandradford.edu
Powered by PLT Scheme