-3

This is my code:

$arr = array();

$dns_1 = mysqli_query($conn, $query);
$dns_2 = mysqli_query($conn, $query);

$d1 = mysqli_fetch_assoc($dns_1);
$d2 = mysqli_fetch_assoc($dns_2);

$arr[1] = $d1;
$arr[2] = $d2;

foreach($arr as $key => $values) {
            echo $key."".$values;
        }

Output:

Notice: Array to string conversion in C:\xampp\htdocs\index.php on line 79
1Array

Why can't I echo the $values in my foreach??

I don't want to use implode if possible

Thank you!

Jheilo
  • 1
  • 2
  • As the notice says, `$values` is an associative array (as defined when you called `mysqli_fetch_assoc()`), not a string. So you either need to do `echo $key." ".implode($values, " ");` or iterate over `$values` and output them individually. – WOUNDEDStevenJones Feb 23 '21 at 04:36
  • What exactly is the purpose of running the same query twice? Or are you changing the query between the two `mysqli_query` calls, but you've omitted it from the question? – El_Vanja Feb 23 '21 at 10:46
  • Does this answer your question? [Array to string conversion](https://stackoverflow.com/questions/26377015/array-to-string-conversion) and https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php – Syscall Feb 26 '21 at 08:27

1 Answers1

3

Because $values is an array, you can't echo it as a string. If you don't want to use implode(), you can use print_r() like this:

foreach($arr as $key => $values) {
    echo $key . ':';
    print_r($value);
}
Kien Nguyen
  • 2,616
  • 2
  • 7
  • 24