0

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?

4
  • 2
    You have a multidimensional array. $result has only one element, at index 0, which is an array. Use $result[0] if you expect only one result from the query. If it can return multiple results, use nested loops. Commented May 18, 2021 at 17:54
  • 1
    Advice for the future: use var_dump instead of print_r. Not only does it structure the dump more nicely, it also contains additional useful information. Commented May 18, 2021 at 17:55
  • $len = count($result);->1 only gives the length of the first string,so how do i get the child's length Commented May 18, 2021 at 18:06
  • By iterating the array and doing the count on the children. Commented May 18, 2021 at 18:20

1 Answer 1

5

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 );
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, your answer is very revealing

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.