Search code examples
phpfunctionreturnresultset

Assign output of PHP function to a variable


Here's my current code:

function get_coins() {
    global $conn;
    $new_sql = "SELECT * FROM marketcaps ORDER BY cap DESC LIMIT 25";
    $new_result = $conn->query($new_sql);
    while ($row = $new_result->fetch_assoc()) {
        $id = $row["id"];
        $coin = $row["coin"];
        $cap = $row["cap"];
        echo $coin . '~USD,';
    }
}

$coins = get_coins();

Here's what I can't figure out:

The line $coins = get_coins(); is echoing all of the data from my function and I don't understand why. I know that my function has this line: echo $coin . '~USD,';

But why is it echoing when I add $coins = get_coins();?

Shouldn't I have to add this instead?

$coins = get_coins();
$echo coins;

Basically I don't want to echo anything, I just want to assign the output to a variable. Is there a simple way to do that?


Solution

  • Here are the principles that I have baked in with my solution which returns the full resultset array:

    • Don't use global, pass $conn as a parameter to the function.
    • Don't declare single use variables, unless it dramatically improves readability or assists in the debugging process.
    • Only query for the specific columns and rows that you intend to process.

    Suggested Code:

    function get_coins($conn): array {
        return $sql
            ->query("SELECT id,coin,cap
                     FROM marketcaps
                     ORDER BY cap DESC
                     LIMIT 25")
            ->fetch_all(MYSQLI_ASSOC);
    }
    
    foreach (get_coins($conn) as $row) {
        // ... reference $row['id'] , $row['coin'] , $row['cap'] during your processes
    }