Search code examples
phpforeachimplode

Array seems empty with Implode on array_values


Some assistance would be greatly appreciated:

The 'foreach' section works perfectly and echo's the result set perfectly; as soon as I try the implode it fails? Thank you!

$ctr = 0;
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {

    $RespondentsResultSetArray[$ctr] = array(
        "Firstname" => $row['cnt_firstname'],
        "Lastname" => $row['cnt_lastname']
    );

    $ctr = $ctr + 1;
}

foreach ($RespondentsResultSetArray as $key) {
    echo $key["Firstname"] . ' ' . $key["Lastname"] . ', ';
}

sqlsrv_free_stmt($stmt);

echo implode(', ',array_values($RespondentsResultSetArray));

Solution

  • You are passing an array of arrays to implode function. Here is a little deviation of your code, that should get you to the same result:

    $full_array = array();
    foreach ($RespondentsResultSetArray as $key) {
        echo $key["Firstname"] . ' ' . $key["Lastname"] . ', ';
        array_push($full_array,$key["Firstname"]);
        array_push($full_array,$key["Lastname"]);
    
    }
    
    
    
    echo implode(', ',$full_array);
    

    Also, for the future, try to chose smaller names for your variables, and use lowercase for your variable names and array index.