My first php code

By hhefestos on Apr 01, 2024

This is to demonstrate that kids can also have fun coding

    <?php
// Define some variables
$greeting = "Hello, ";
$name = "John";
$age = 30;
$city = "New York";

// Concatenate variables and create a message
$message = $greeting . $name . "! You are " . $age . " years old and live in " . $city . ".";

// Define an array of fruits
$fruits = array("Apple", "Banana", "Orange", "Mango", "Grape");

// Loop through the array and echo each fruit
foreach ($fruits as $fruit) {
    echo "I like " . $fruit . "s.<br>";
}

// Define a function to calculate the square of a number
function square($num) {
    return $num * $num;
}

// Calculate the square of 5 using the function
$square_of_5 = square(5);

// Echo the result
echo "The square of 5 is " . $square_of_5 . ".";

// Define a class for a simple calculator
class Calculator {
    // Properties
    public $num1;
    public $num2;

    // Constructor
    function __construct($num1, $num2) {
        $this->num1 = $num1;
        $this->num2 = $num2;
    }

    // Method to add two numbers
    function add() {
        return $this->num1 + $this->num2;
    }

    // Method to subtract two numbers
    function subtract() {
        return $this->num1 - $this->num2;
    }
}

// Create a new instance of the Calculator class
$calculator = new Calculator(10, 5);

// Call the add and subtract methods
$sum = $calculator->add();
$difference = $calculator->subtract();

// Echo the results
echo "The sum is " . $sum . ".<br>";
echo "The difference is " . $difference . ".";
?>

Comments

Sign in to comment.
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.