Aaron Saray

open source programmer,
web developer

entrepreneur, author
and musician

My Blog

contains PHP, Web and business/entrepreneurial related content. Please join in the conversation!

When is a PHP array not an array?

Arrays, return variables, expressions, OH MY! I recently learned a lesson about array functions in PHP not returning what I thought they would. I had a function that returned the value of array_shift()… and then used it in another function. Unfortunately, this generated a strict error and was causing some issues… As usual, I put together a proof of concept. Lets check out the code example, the error, and then why:

__data = 'one,two,three';
    }

    public function getArray()
    {
        $a = array();

        $a[] = explode(',', $this->__data);
        $a[] = explode(',', $this->__data);
        $a[] = explode(',', $this->__data);

        return $a;
    }
}

function testFunction()
{
    $test = new TEST();

    return array_shift($test->getArray());
}

var_dump(testFunction());

?>

When I execute this, I get a strict error:

Strict Standards: Only variables should be passed by reference in C:\DEVELOPMENT\temp\arraytest.php on line 27 array(3) { [0]=> string(3) “one” [1]=> string(3) “two” [2]=> string(5) “three” }

After talking with one of the consultants that (“the triangle”) uses, he sent me a note about all the things he found in regards to my test code.

First off, this bug page is from another developer that was running into the same issues as I was. After some back and forth, it looks like its just a mis-understanding … those functions are returning array pointers and not values and expressions (see expressions in PHP manual here).

Turns out that the way to fix this issue is going to be using pass by reference. One quick modification and we’re good:

1
public function &getArray()

This entry was posted in PHP and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>