Jump to content

Programming Fundamentals/Arrays/PHP

From Wikiversity

arrays.php

[edit | edit source]
<?php

// This program uses arrays to display temperature conversion tables 
// and temperature as an array subscript to find a given conversion.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://en.wikibooks.org/wiki/PHP_Programming

function build_c($size)
{
    $c = array();

    for ($index = 0; $index <= $size; $index++)
    {
        $value = $index * 9 / 5 + 32;
        $c[$index] = $value;
    }
    
    return $c;
}

function build_f($size)
{
    $f = array();

    for ($index = 0; $index <= $size; $index++)
    {
        $value = ($index - 32) * 5 / 9;
        $f[$index] = $value;
    }
    
    return $f;
}

function display_array($name, $array)
{
    for ($index = 0; $index < count($array); $index++)
    {
        echo($name . "[" . $index . "] = " . $array[$index] ."\n");
    }
}

function find_temperature($c, $f)
{
    $size = minimum(count($c), count($f));
    do
    {
        echo("Enter a temperature between 1 and " . ($size - 1) . "\n");
        $temp = (int)readline();
    } while ($temp < 1 or $temp > $size - 1);
    echo($temp . "° Celsius is " . $c[$temp] . "° Fahrenheit\n");
    echo($temp . "° Fahrenheit is " . $f[$temp] . "° Celsius\n");
}

function minimum($value1, $value2)
{
    if($value1 < $value2)
    {
        $result = $value1;
    }
    else
    {
        $result = $value2;
    }
        
    return $result;
}

function main()
{
  $c = build_c(100);
  $f = build_f(212);
  display_array("C", $c);
  display_array("F", $f);
  find_temperature($c, $f);
}

main();

?>

Try It

[edit | edit source]

Copy and paste the code above into one of the following free online development environments or use your own PHP compiler / interpreter / IDE.

See Also

[edit | edit source]