Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Return a reference to an array element

Tags:

arrays

php

Is there a way in PHP to return a reference to an element in array?

function ref(&$array, &$ref) { $ref = $array[1]; }
$array = array(00, 11, 22, 33, 44, 55, 66, 77, 88, 99);
ref($array, $ref);
$ref = 'xxxxxxxxxx';
var_dump($ref);
var_dump($array);

I expect that $array will be changed as in the following code:

$array = array(00, 11, 22, 33, 44, 55, 66, 77, 88, 99);
$ref = &$array[1];
$ref = 'xxxxxxxxxx';
var_dump($ref);
var_dump($array);
like image 997
vbarbarosh Avatar asked Apr 10 '14 10:04

vbarbarosh


People also ask

How do you return an array of objects in PHP?

Method 1: Using json_decode and json_encode method: The json_decode function accepts JSON encoded string and converts it into a PHP variable on the other hand json_encode returns a JSON encoded string for a given value. Syntax: $myArray = json_decode(json_encode($object), true);

Does PHP pass arrays by reference?

With regards to your first question, the array is passed by reference UNLESS it is modified within the method / function you're calling. If you attempt to modify the array within the method / function, a copy of it is made first, and then only the copy is modified.

What is return $this in PHP?

$this means the current object, the one the method is currently being run on. By returning $this a reference to the object the method is working gets sent back to the calling function.

Can PHP return array?

Any type may be returned, including arrays and objects.


1 Answers

I've found two ways to return reference to an array element:

1. Using return by reference and =&

    function & ref(&$array)
    {
            return $array[1];
    }

    $array = array(00, 11, 22, 33, 44, 55, 66, 77, 88, 99);
    $ref =& ref($array);
    $ref = 'xxxxxxxxx';
    var_dump($ref);
    var_dump($array);

2. Put reference into an array

    function ref(&$array, &$ref = array())
    {
            $ref = array();
            $ref[] = &$array[1];
    }

    $array = array(00, 11, 22, 33, 44, 55, 66, 77, 88, 99);
    ref($array, $ref);
    $ref[0] = 'xxxxxxxxx';
    var_dump($ref);
    var_dump($array);
like image 154
vbarbarosh Avatar answered Oct 11 '22 02:10

vbarbarosh