Pure Rhymer Organization Pure Rhymer Organization - 1 month ago 20
PHP Question

while looping vs foreach looping

Im trying to print it in excel but I dont get it why the foreach loop give me an Warning: Illegal string offset but in while loop it just run smoothly

this is the while loop

EDITED

include 'db.php';
$sql = "SELECT * FROM customer";
$result = mysql_query($sql);
$excel = array();

while($row = mysql_fetch_array($result)){
$wew = $row["fname"]."\t".$row["lname"]."\t".$row["email"];
array_push($excel,$wew);
}

echo implode("\n",array_values($excel));


This is my foreach loop

include 'db.php';
$sql = "SELECT * FROM customer";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$excel = array();

foreach($row as $r){
$wew = $r["fname"]."\t".$r["lname"]."\t".$r["email"];
array_push($excel,$wew);
}

echo implode("\n",array_values($excel));


Im trying to understand it but couldn't find how solve this one.

Answer

Your $r is of string type and not an array so:

foreach($row as $r){
    $wew = $row["fname"]."\t".$row["lname"]."\t".$row["email"];
    array_push($excel,$wew);
}

OR

$wew = "";
foreach($row as $r){
    $wew .= $row["fname"]."\t".$row["lname"]."\t".$row["email"]; 
}
array_push($excel,$wew);