Home >> FAQs/Tutorials >> PHP Script Tutorials and Tips >> Index

PHP Script Tips - Creating Your Own Functions

By: FYICenter.com

Part:   1  2  3   4  5 

(Continued from previous part...)

How Arrays Are Passed Through Arguments?

Like a normal variable, an array is passed through an argument by value, not by reference. That means when an array is passed as an argument, a copy of the array will be passed into the function. Modifying that copy inside the function will not impact the original copy. Here is a PHP script on passing arrays by values:

<?php
function shrink($array) {
  array_splice($array,1);
}
$numbers = array(5, 7, 6, 2, 1, 3, 4, 2);
print("Before shrinking: ".join(",",$numbers)."\n");
shrink($numbers);
print("After shrinking: ".join(",",$numbers)."\n");
?>

This script will print:

Before shrinking: 5,7,6,2,1,3,4,2
After shrinking: 5,7,6,2,1,3,4,2

As you can see, original variables were not affected.

How To Pass Arrays By References?

Like normal variables, you can pass an array by reference into a function by taking a reference of the original array, and passing the reference to the function. Here is a PHP script on how to pass array as reference:

<?php 
function shrink($array) {
  array_splice($array,1);
}
$numbers = array(5, 7, 6, 2, 1, 3, 4, 2);
print("Before shrinking: ".join(",",$numbers)."\n");
shrink(&$numbers);
print("After shrinking: ".join(",",$numbers)."\n");
?>

This script will print:

Before shrinking: 5,7,6,2,1,3,4,2
After shrinking: 5

Note that call-time pass-by-reference has been deprecated. You need to define arguments as references. See next tip for details.

Can You Define an Array Argument as a Reference Type?

You can define an array argument as a reference type in the function definition. This will automatically convert the calling arguments into references. Here is a PHP script on how to define an array argument as a reference type:

<?php
function ref_shrink(&$array) {
  array_splice($array,1);
}
$numbers = array(5, 7, 6, 2, 1, 3, 4, 2);
print("Before shrinking: ".join(",",$numbers)."\n");
ref_shrink($numbers);
print("After shrinking: ".join(",",$numbers)."\n");
?>

This script will print:

BBefore shrinking: 5,7,6,2,1,3,4,2
After shrinking: 5

How To Return an Array from a Function?

You can return an array variable like a normal variable using the return statement. No special syntax needed. Here is a PHP script on how to return an array from a function:

<?php
function powerBall() {
  $array = array(rand(1,55), rand(1,55), rand(1,55), 
                 rand(1,55), rand(1,55), rand(1,42));
  return $array;    
}
$numbers = powerBall();
print("Lucky numbers: ".join(",",$numbers)."\n");
?>

This script will print:

Lucky numbers: 35,24,15,7,26,15

If you like those nummers, take them to buy a PowerBall ticket.

(Continued on next part...)

Part:   1  2  3   4  5 


Selected Developer Jobs:

More...