-1

So I'm trying to create an array inside a loop so that I can use its elements elsewhere in the code ...

And so when I try to var_dump the array to see if all the expected elements have been added into the array , I only see the last element of the array inside the new array .. Could anyone explain me why ... Below is the relevant part of the code

$select  = "SELECT * FROM DEVICES";
$result = mysql_query($select);
$result_count = mysql_num_rows($result)

if($result_count > 0) {
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

        echo "<td> <a class='inline' href='/profiles.php?id=".$row['ID']."'><img src='".$row['Picture']."'width='50' height='50' class ='image' /></a> <br /> <br /> <div style='color: blue; font-weight:bold; font-size:15px;'> By ".$row['Name']." </td>";
        $user_array = array();
        if(array_key_exists("Device",$row)){
            array_push ($user_array,$row["Device"]);
        }    
    }
}
var_dump($user_array);  // only returns the last element inserted into $user_array.
hakre
  • 193,403
  • 52
  • 435
  • 836
  • Trouble shooting these issues are most comfortable by using a remote debugger, for example xdebug in PHP: http://xdebug.org/docs/remote – hakre Jun 23 '13 at 11:38
  • X-Ref same type of mistake: http://stackoverflow.com/q/17140454/367456 – hakre Jun 23 '13 at 15:50
  • [**Please, don't use `mysql_*` functions in new code**](http://bit.ly/phpmsql). They are no longer maintained [and are officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the [**red box**](http://j.mp/Te9zIL)? Learn about [*prepared statements*](http://j.mp/T9hLWi) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://j.mp/QEx8IB) will help you decide which. If you choose PDO, [here is a good tutorial](http://j.mp/PoWehJ). – Madara's Ghost Jun 23 '13 at 16:43

2 Answers2

4

The issue is that you are resetting the array every time the body of the while loop executes.

You have to initialize the array outside of the loop:

$user_array = array();

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

    echo "<td> <a class='inline' href='/profiles.php?id=".$row['ID']."'><img src='".$row['Picture']."'width='50' height='50' class ='image' /></a> <br /> <br /> <div style='color: blue; font-weight:bold; font-size:15px;'> By ".$row['Name']." </td>";

    if(array_key_exists("Device",$row)) {
        array_push ($user_array,$row["Device"]);
    }    
}

var_dump($user_array);
KaeruCT
  • 1,605
  • 14
  • 15
0

try this, more simple.

$user_array = array();
if (isset($row["Device"]) && !empty($row["Device"])) {
  $user_array[] = $row["Device"];
}

and you have clean array with data.

print_r($user_array);
Dino Babu
  • 5,814
  • 3
  • 24
  • 33
  • Using [`isset() && !empty()`](https://stackoverflow.com/a/4559976/2943403) is an antipattern that should not be in anyone's code for any reason. – mickmackusa Oct 25 '22 at 21:53