PHP behind the page: isset and the ready converters
PHP code sits between <?php and ?>. The server runs it before the page is sent, so the visitor never sees it. The values of the form arrive in $_POST under the names we gave: $_POST['number'] is the typed text. When the page is opened for the first time nothing was sent. When a button is pressed its name arrives too, so isset($_POST['btnBin']) is true only if that button was pressed, and each button gets its own if block. Inside the block the code reads the typed number and fills four variables: the typed text, and the binary, decimal and hexadecimal results. Four ready functions do the conversions: bindec reads binary text and gives a number, decbin writes a number in binary, hexdec reads hexadecimal text and dechex writes a number in hexadecimal. None of these four goes straight from binary to hexadecimal, so the page goes through decimal: bindec first, then dechex. The ready functions write hexadecimal in lower case.
| Function | Reads | Gives | Example |
|---|---|---|---|
| bindec | binary text | a number | bindec("1101") = 13 |
| decbin | a number | binary text | decbin(90) = 1011010 |
| hexdec | hexadecimal text | a number | hexdec("3C") = 60 |
| dechex | a number | hexadecimal text, lower case | dechex(200) = c8 |
1<?php 2$_POST = ['btnBin' => 'Typed number is binary', 'number' => '1101']; // pretend the form was sent 3$typed = ""; 4$bin = ""; 5$dec = ""; 6$hex = ""; 7 8if (isset($_POST['btnBin'])) { 9 $typed = $_POST['number']; 10 $dec = bindec($typed); 11 $bin = $typed; 12 $hex = dechex($dec); 13} 14echo "$bin $dec $hex";
1101 13 d
1<?php 2$typed = ""; 3$bin = ""; 4$dec = ""; 5$hex = ""; 6 7if (isset($_POST['btnBin'])) { 8 $typed = $_POST['number']; 9 $dec = bindec($typed); 10 $bin = $typed; 11 $hex = dechex($dec); 12} 13if (isset($_POST['btnDec'])) { 14 $typed = $_POST['number']; 15 $dec = $typed; 16 $bin = decbin($dec); 17 $hex = dechex($dec); 18} 19if (isset($_POST['btnHex'])) { 20 $typed = $_POST['number']; 21 $dec = hexdec($typed); 22 $bin = decbin($dec); 23 $hex = $typed; 24} 25?>
| Button | Typed | Binary | Decimal | Hexadecimal |
|---|---|---|---|---|
| btnBin | 1101 | 1101 | 13 | d |
| btnDec | 90 | 1011010 | 90 | 5a |
| btnHex | 3C | 111100 | 60 | 3C |
Predict on paper the three results when the visitor types 200 and presses the decimal button, and then when the visitor types B4 and presses the hexadecimal button. Check each answer by converting back.