PHP

Syntax of PHP

Pratik Kabade, 01 June 2022

PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1994. The PHP reference implementation is now produced by The PHP Group.

Content

  1. Basics
  2. Array
  3. Class
  4. String
  5. Constants
  6. If Else
  7. Switch
  8. Loops
  9. Numbers

1 Basics

$txt = "PHP";
echo "This is $txt! <br>";
$x = 5;
$y = 4;
echo "Addition is: ";
echo $x + $y;
print "<br><a>PHP is Fun!</a>";

2 Array

var_dump

$cars = array("Volvo","BMW","Toyota");
var_dump($cars);

define

define("cars", [
"Alfa Romeo",
"BMW",
"Toyota"
]);
echo cars[0];

3 Class

class Car {
public $color;
public $model;
public function __construct($color, $model) {
    $this->color = $color;
    $this->model = $model;
}
public function message() {
    return "My car is a " . $this->color . " " . $this->model . "!";
}
}

$myCar = new Car("black", "Volvo");
echo $myCar -> message();
echo "<br>";
$myCar = new Car("red", "Toyota");
echo $myCar -> message();

4 String

echo strrev("Hello world!");

echo strpos("Hello world!", "world");

echo str_replace("world", "Dolly", "Hello world!");

5 Constants

define("GREETING1", "Welcome to PHP!");
echo GREETING1;

define("GREETING2", "Welcome to PHP!");
function myTest() {
echo GREETING2;
}
myTest();

6 If Else

$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}

$t = date("H");

if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}

7 Switch

$favcolor = "red";
switch ($favcolor) {
case "red":
    echo "Your favorite color is red!";
    break;
case "blue":
    echo "Your favorite color is blue!";
    break;
case "green":
    echo "Your favorite color is green!";
    break;
default:
    echo "Your favorite color is neither red, blue, nor green!";
}

8. Loops

while

    $x = 30;
    while($x <= 50) {
    echo "The number is: $x <br>";
    $x+=10;
    }
    ?>

do while

    $x = 6;
    do {
    echo "The number is: $x <br>";
    $x++;
    } while ($x <= 5);
    ?>

for

    for ($x = 70; $x <= 100; $x+=10) {
    echo "The number is: $x <br>";
    }
    ?>

foreach

    $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
    foreach($age as $x => $val) {
    echo "$x = $val<br>";
    }
    ?>

for

    for ($x = 1; $x < 10; $x++) {
    if ($x == 4) {
        break;
    }
    echo "The number is: $x <br>";
    }
    ?>

for

    for ($x = 7; $x < 10; $x++) {
    if ($x == 4) {
        continue;
    }
    echo "The number is: $x <br>";
    }

9. Numbers

$x = 10.365;
var_dump(is_float($x));
echo(min(0, 150, 30, 20, -8, -200));  // returns -200
echo(max(0, 150, 30, 20, -8, -200));  // returns 150
echo(abs(-6.7));  // returns 6.7
echo(sqrt(64));  // returns 8
echo(round(0.60));
echo "<br>";
echo(round(0.49));
echo(rand());
echo(rand(10, 100));