Reputation: 158
I have an array:
Array (
[0] => Array (
[userid] => 5
[0] => 5
[firstname] => DALPA
[1] => DALPA
[lastname] => DALPA
[2] => DALPA
)
)
when i try to print this using foreach loop i get an error
<?php
include('../conn.php');
$q = $_GET['q'];
$adress = $conn->prepare("SELECT * FROM user WHERE firstname= :q ");
$adress->bindValue(':q', $q, PDO::PARAM_STR);
$adress->execute();
$result = $adress->fetchAll();
foreach($result as $item){
echo $item . "\n";
}
?>
Error:Array to string conversion in C:\xampp\htdocs\admin\adres\adres.php on line 13
Been asked many times but none of them solved my problem, what should I do?
Upvotes: 0
Views: 69
Reputation: 7299
php's
echo statement can only echo strings. If it is not a string but a number for example, it will try to converse the given value to a string. With an array that is not possible.
In your case you are looping trough an array
containing another array
. As the error tells you, it fails to echo an array because it expects something that can be converted to a string.
So either use
foreach($result as $item) {
print_r($item) // or var_dump($item)
}
Or echo key => value
pairs using
foreach($result as $item) {
echo $item['firstname'] . "\n";
echo $item['lastname'] . "\n";
... and so on
}
If you are expecting only one item
to be returned, update your query by using fetch
instead of fetchAll
, which will return only one row.
You can then omit the unnecessary foreach loop.
And if you realy want to echo the array, you have to do the conversion manualy by using json_encode
, which will convert the array to an JSON
string.
echo json_encode( $result );
Upvotes: 5