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 Variables Are Passed Through Arguments?

Like more of other programming languages, variables are passed through arguments by values, not by references. That means when a variable is passed as an argument, a copy of the value 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 variables by values:

<?php
function swap($a, $b) {
  $t = $a; 
  $a = $b;
  $b = $t;
}
$x = "PHP";
$y = "JSP";
print("Before swapping: $x, $y\n");
swap($x, $y);
print("After swapping: $x, $y\n");
?>

This script will print:

Before swapping: PHP, JSP
After swapping: PHP, JSP

As you can see, original variables were not affected.

How To Pass Variables By References?

You can pass a variable by reference to a function by taking the reference of the original variable, and passing that reference as the calling argument. Here is a PHP script on how to use pass variables by references:

<?php
function swap($a, $b) {
  $t = $a; 
  $a = $b;
  $b = $t;
}
$x = "PHP";
$y = "JSP";
print("Before swapping: $x, $y\n");
swap(&$x, &$y);
print("After swapping: $x, $y\n");
?>

This script will print:

Before swapping: PHP, JSP
After swapping: JSP, PHP

As you can see, the function modified the original variable.

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 Argument as a Reference Type?

You can define an 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 argument as a reference type:

<?php
function ref_swap(&$a, &$b) {
  $t = $a; 
  $a = $b;
  $b = $t;
}
$x = "PHP";
$y = "JSP";
print("Before swapping: $x, $y\n");
ref_swap($x, $y);
print("After swapping: $x, $y\n");
?>

This script will print:

Before swapping: PHP, JSP
After swapping: JSP, PHP

Can You Pass an Array into a Function?

You can pass an array into a function in the same as a normal variable. No special syntax needed. Here is a PHP script on how to pass an array to a function:

<?php
function average($array) {
  $sum = array_sum($array);
  $count = count($array);
  return $sum/$count;
}
$numbers = array(5, 7, 6, 2, 1, 3, 4, 2);
print("Average: ".average($numbers)."\n");
?>

This script will print:

Average: 3.75

(Continued on next part...)

Part:   1  2   3  4  5 


Selected Developer Jobs:

More...