Albert
Albert

Reputation: 3

How to return a function inside a function

Make a function has_twenty_ones that returns true if at least one of the players in the game has 21, otherwise return false. This function should use the twenty_ones function.

function has_twenty_ones($game){
    function twenty_ones($game)
    {
        $players_with_score_21 = [];
        foreach ($game['players'] as $name => $player) {
            $distance = 21 - $player['score'];
            if ($distance < 0) {
                continue;
            }
            if ($distance == 21) {
                $players_with_score_21 = [$name];
            }
        }
        return $players_with_score_21;
    }
    return isset($players_with_score_21);

}

what's the best way to code it

Upvotes: 0

Views: 59

Answers (3)

VenomRush
VenomRush

Reputation: 1682

I'm not sure why you need two functions for this.

As was mentioned by @RiggsFolly, you're not actually making a call to twenty_ones() function. Why not have the following code:

function has_twenty_ones($game)
{
    foreach($game['players'] as $name => $player)
    {
        $distance = 21 - $player['score'];
        if ($distance < 0) {
            continue;
        }
        // If at least one player has 21, return true.
        if($distance == 21) {
            return true;
        }
    }
    return false;
}

The above will return true when it encounters a player who has a score of 21, otherwise it'll return false.

Upvotes: 0

Afaf
Afaf

Reputation: 654

function twenty_ones($game)
{
    $players_with_score_21 = [];
    foreach ($game['players'] as $name => $player) {
       $distance = 21 - $player['score'];
       if ($distance < 0) {
        continue;
       }
       if ($distance == 21) {
                    $players_with_score_21 = [$name];
       }
    }
    return $players_with_score_21;
}

function has_twenty_ones($game){
    if (count ($this->twenty_ones($game)) > 0 )
        return true;
    else 
       return false;
}

Upvotes: -1

Kacper Polak
Kacper Polak

Reputation: 1411

Just check if return of twenty_ones function is empty, if it return false overthose return twenty_ones value.

function has_twenty_ones($game){
    function twenty_ones($game){
        $players_with_score_21 = [];
        foreach ($game['players'] as $name => $player) {
            $distance = 21 - $player['score'];
            if ($distance < 0) {
                continue;
            }
            if ($distance == 21) {
                $players_with_score_21 = [$name];
            }
        }
        return $players_with_score_21;
    }
    $playersWithScore = twenty_ones($game);
    if (!empty($playersWithScore)) {
       return $playersWithScore;
    } else {
      return false;
    } 
}

Upvotes: 2

Related Questions