user5563910
user5563910

Reputation:

How to get value of item in array

I am querying a database which returns an array. How can I then echo out a value from the array?

I have tried the following but I can't get it to work:

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
      print_r(array_values($row));
      echo $row[0]['4'];
     }
}

The result of print_r(array_values($row)) is:

Array ( [0] => 0.0 [1] => 0.0 [2] => 25.0 [3] => 26.0 [4] => 1029.4 [5] => 0.0 [6] => 67.8 [7] => 26.0 [8] => 137.5 [9] => 1133.8 [10] => 0.0 [11] => 0.0 [12] => 13.1 [13] => 68.7 [14] => 0.0 [15] => 0.0 [16] => 1.2 [17] => 0.0 [18] => 0.0 [19] => 0.0 [20] => 0.0 [21] => 0.0 [22] => 0.0 [23] => 0.0 [24] => 0 [25] => 0 )

How can I display the value of item [3] which should be 26.0 ? Any help would be greatly appreciated.

Upvotes: 2

Views: 70

Answers (3)

M.Be
M.Be

Reputation: 322

This one will echo all values

// If you had at least one row
if($result->rowCount() > 0) {
    // iterate over results
    while($record = $result->fetchAssoc()) {
        foreach($record as $column_record) {
            echo $column_record;
        }
    }
}

To echo only the value of the key "3" in each row, you can modify this in

// If you had at least one row
if($result->rowCount() > 0) {
    // iterate over results
    while($record = $result->fetchAssoc()) {
        echo $record[3];
    }
}

If no error, this will do the job ;)

Upvotes: 0

andre
andre

Reputation: 194

Your $row is an associative array, array_values removes the keys from the array. You get the result by either doing:

$arrayValues = array_values($row)
echo $arrayValues[4];

or (better)

echo $row['col4']; 

(in which col4 is the columnname in the table);

Upvotes: 1

dimlucas
dimlucas

Reputation: 5131

It's pretty simple actually.

To access the values of an array you use the indexer operator [].

So the value 26 resides in $row[3]

You can display it on screen like this:

echo $row[3];

Upvotes: 0

Related Questions