Search code examples
phparraysdeep-copy

PHP: functions that return arrays: how to get a exact copy of returned array


When a function in php returns an array and I assign it to a varialble such a 'user' bellow. It copies the array and put it space [0]

$user = query("SELECT * FROM `users` WHERE id = ?", $_SESSION["id"]);



Array
(
    [0] => Array
        (
            [cash] => 127046553.2710
            [id] => 8
            [username] => test
            [hash] => $1$w40Hc/vl$45jJlZ/1x1rqQlEEQP7hE1
        )

)

So then I have to do this:

if ($user[0]["cash"])

But it would be better do just ask the array for "cash". What is the standard way of doing this in php?

if ($user["cash"])

Solution

  • This is because of the function 'query' you use.

    The function does return (I would guess) an array of all returned rows. So if there would be more users you would get 0=>user1, 1=>user2, etcetera.

    If you're sure that you will only get one user you can do the following:

    $user = query("SELECT * FROM `users` WHERE id = ?", $_SESSION["id"]);
    $user = $user[0];