Skip to content
PHP Logo

How can PHP be used to determine the probability of a certain result occurring?

To determine the probability of a certain result occurring, we can use a mathematical formula such as the probability formula which is the number of desired outcomes divided by the total number of possible outcomes. In PHP, we can write a function that takes the desired outcomes and total outcomes as input parameters, and then calculates and returns the probability.

php
function calculateProbability($desiredOutcomes, $totalOutcomes) {
    $probability = $desiredOutcomes / $totalOutcomes;
    return $probability;
}

// Example of calculating the probability of rolling a 6 on a fair six-sided die
$desiredOutcomes = 1; // rolling a 6
$totalOutcomes = 6; // possible outcomes on a six-sided die
$probability = calculateProbability($desiredOutcomes, $totalOutcomes);

echo "The probability of rolling a 6 on a fair six-sided die is: " . $probability;