简体   繁体   中英

PHP: difference between array and variable containing an array?

In this [I-believe] famous loop condition ($row = $result->fetch()) (in which $result is a PDOStatement object) what is the type of the $row? Is it an "array" or an "array container"? Is there a difference between an array and a variable that holds an array?!

I ask this specially because if there wasn't any difference, then I should have been able to have my rows the whole in the $row variable after the loop is done, which is not the case, and I need another array to hold each row for me(the syntax is also different and I need empty brackets in front of the name of that array to add elements)

(According to my tutorial, fetch() is a method of the PDOStatement object that returns the next row of my table as an array ).

Actually

$row is a run-time array variable which is re-created each time when loop ( while loop) runs.So previous values will not be available. That's why you have to save it's data to another array variable which is created statically.

Is this recreation an intrinsic quality of the while loop?

Simon.B no it's not. You can try

$row = []; 
while($row[] = $result->fetch()){};
print_r($row); 

and check.

Better alternative is to use fetchAll();

But why this above apporach is not used often:-

Because above approach will load the whole array again and again into Memory when loop runs and then assign array to that.

While when you are using run-time variable and doing assignment then the whole array is not loaded each time, only assignment will done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM