Objective
Output three input numbers in ascending order.
Description
Ask the user to input three different integers by means of three different input prompts.
The general form of all the three input prompts together is shown as follows:
y: <input>
z: <input>
Once this is done, finally output these numbers in ascending order (i.e. smallest number first, largest number last) in the following format .
Where <int1>
, <int2>
, and <int3>
, are the input numbers.
Below shown is an example:
y: 32
z: 50
New file
Inside the directory you created for this course on PHP, create a new folder called Exercise-3-Sorted-Numbers and put the .php solution files for this exercise within it.
Solution
We need to get three inputs from the user, hence we start by laying out three different fgets()
calls preceded by the respective prompt messages:
<?php
$nums = [];
echo 'x: ';
array_push($nums, (int) fgets(STDIN));
echo 'y: ';
array_push($nums, (int) fgets(STDIN));
echo 'z: ';
array_push($nums, (int) fgets(STDIN));
Take note of the (int)
typecast before each fgets()
call — this is done to make it apparent programmatically and visibly that we want to add the input number to the array $nums
in the form of an integer.
fgets()
always returns a string.After obtaining the inputs, the next step is to sort the $nums
array. This is done below:
<?php
$nums = [];
echo 'x: ';
array_push($nums, (int) fgets(STDIN));
echo 'y: ';
array_push($nums, (int) fgets(STDIN));
echo 'z: ';
array_push($nums, (int) fgets(STDIN));
// Sort the numbers.
sort($nums);
echo 'Sorted numbers: ', $nums[0], ' ', $nums[1], ' ', $nums[2];
To end with, we print all the three elements of the array (which is now in sorted order), one after another making sure that the desirable format of the output as indicated in the exercise's question is followed:
<?php
$nums = [];
echo 'x: ';
array_push($nums, (int) fgets(STDIN));
echo 'y: ';
array_push($nums, (int) fgets(STDIN));
echo 'z: ';
array_push($nums, (int) fgets(STDIN));
// Sort the numbers.
sort($nums);
echo 'Sorted numbers: ', $nums[0], ' ', $nums[1], ' ', $nums[2];
This completes our exercise!