Search code examples
phpfor-loopreturnecho

why am i only getting the first row value in array "row" in the below code. i need all the values corresponding to the query


  $s = $conn->prepare($q);
  $s->execute([$tagIdValue]);
  $d = $s->fetchAll();
  return $d;

function x($d) {
    foreach ($d as $row) {
      $val = $row["id"];
      $cont = trimContent($row);
      return $row;
    }
  }

i have a query , which returns all the values in the table and a function to convert it into an assosiate array. But only getting the first row in the array


Solution

  • Because ur using return inside loop, it only take first value and return it.

      $s = $conn->prepare($q);
      $s->execute([$tagIdValue]);
      $d = $s->fetchAll();
      return $d;
    
    function x($d) {
        $arr =[]
        foreach ($d as $row) {
          $val = $row["id"];
          $cont = trimContent($row);
          array_push($arr, $val)
        }
       return $arr;
      }