Exponentiation Operator
Part of the Fundamentals section of Coddy's PHP journey — lesson 17 of 71.
The exponentiation operator (**) raises a number to a power. It's a cleaner way to write "multiply a number by itself" a certain number of times.
<?php
echo 2 ** 3; // Outputs: 8
?>Here, 2 ** 3 means 2 raised to the power of 3, which is 2 × 2 × 2 = 8. The first number is the base, and the second is the exponent.
<?php
$base = 5;
$exponent = 2;
$result = $base ** $exponent;
echo $result; // Outputs: 25
?>You can also use this operator with decimal exponents. For example, raising a number to the power of 0.5 gives you its square root:
<?php
echo 16 ** 0.5; // Outputs: 4
echo 9 ** 0.5; // Outputs: 3
?>Challenge
EasyRead two numbers from input: a base and an exponent.
Calculate and print the result of raising the base to the power of the exponent using the exponentiation operator.
Example:
If the inputs are 3 and 4, the output should be 81 (because 34 = 3 × 3 × 3 × 3 = 81).
Cheat sheet
The exponentiation operator (**) raises a number to a power:
<?php
echo 2 ** 3; // Outputs: 8 (2 × 2 × 2)
?>The first number is the base, and the second is the exponent.
<?php
$base = 5;
$exponent = 2;
$result = $base ** $exponent;
echo $result; // Outputs: 25
?>Decimal exponents are also supported. For example, raising a number to the power of 0.5 gives its square root:
<?php
echo 16 ** 0.5; // Outputs: 4
echo 9 ** 0.5; // Outputs: 3
?>Try it yourself
<?php
// Read input
$base = intval(fgets(STDIN));
$exponent = intval(fgets(STDIN));
// TODO: Write your code below to calculate base raised to the power of exponent
// Output the result
echo $result;
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison OperatorsEquality & IdentityLogical Operators Part 1Logical Operators Part 2Recap - Simple Logic2Variables and Data Types
NumbersStrings and QuotesBooleansNaming ConventionsRecap - Variable InitEmpty VariablesString ConcatenationGetting User InputCast to Different Types5Conditional Logic
If StatementIf - ElseThe Ternary OperatorNull Coalescing OperatorSwitch StatementRecap - Making Decisions3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString Operators