Passing Arrays by References to Functions in PHP

Q

How To Pass Arrays By References? in PHP?

✍: FYIcenter.com

A

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.

 

Creating Your Own Functions in PHP

⇒⇒PHP Tutorials

2016-12-18, 331👍, 0💬