CodeBlanks Logo Icon CodeBlanks

Number input and operator selection

PHP course · Beginner · Lesson 20/116

Take two numbers and an operator to set up the operation.

Variables for the numbers

The calculator keeps two numbers in variables. We use $first for the first number and $second for the second. We declare variables by assigning a value with the = sign.

We can write numbers directly as integers (int). For example, $first = 25; assigns 25 to $first. Variable names are case sensitive in PHP, so $first and $First are different variables.

The operator is stored as a string

The operator character (+, -, *, /) is stored as a string. These characters represent a choice, not a numeric value. $operator = "+"; sets the operator to addition.

We write string values inside double quotes. Later we'll compare the $operator variable with an if structure to pick the right operation. For now we just declare the variable and print it.

Exercise Add the operator and the second number

Now add the operator and the second number. Assign "+" to $operator and 4 to $second. Then print all three variables separated by spaces.

Show example solution
Declare the operator as a string and the second number as an int.
Example solution:
<?php
// The first number entered by the user
$first = 25;
// The chosen operator and second number
$operator = "+";
$second = 4;
echo $first . " " . $operator . " " . $second;

Test yourself

  1. Which variable holds the operator?

    <?php
    $first = 25;
    $operator = "+";
    $second = 4;
    • $operator
    • $first
    • $second
    • $result
    Show answer

    $operator — $operator holds the chosen operation (+, -, *, /).

  2. Assign the addition value to the operator

    <?php
    $operator = ____;
    echo $operator;
    ?>
    Show answer
    <?php
    $operator = "+";
    echo $operator;
    ?>
  3. Match each variable to its role

    $first
    First number
    $operator
    Chosen operator
    $second
    Second number

All lessons in Beginner