Syntax is very simple, similar to that of Python or other C based languages. Variables are created by a simple $ in front of the name of the variable. Each line must end in a semi-colon.
<?php
$new_variable = "Hello World";
echo $new_variable;
?>
To display to screen we use the “echo” function, print() is also available
We have a few to choose from: - String - Integer - Float/Double - Array - Object - NULL - Resource We can use the built in function “var_dump()” to find the data type of a variable.
<?php
$x = 200;
var_dump($x);
?>
---Output---
Int(200)
Strings are important! Because PHP is a hypertext markdown language, commonly used in conjunction with HTML. In PHP we can use HTML tags as if we were using them in HTML. I find it to be very convenient and interesting.
So for example, I often use <br> to separate
outputs and make new lines.
<?php
$x = "Hello";
$y = "World";
echo "$x<br>$y";
?>
---Output---
Hello
World
<?php
$x = "Hello World!";
$y = explode(" ", $x);
print_r($y);
?>
---Output---
Array ( [0] => Hello [1] => World! )
String manipulation is pretty straight forward
Concatenation To combine strings we can use the ’ . ’ operator as well as a few other options. I prefer the 3rd option, its easier.
</php
$x = "Hello";
$y = "World";
$z = $x . $y;
echo $z;
---Output---
HelloWorld
-=-=-=-=-=-=-=-=-=-=-
$x = "Hello";
$y = "World";
$z = $x . " " . $y;
echo $z;
---Output---
Hello World
-=-=-=-=-=-=-=-=-=-=-
$x = "Hello";
$y = "World";
$z = "$x $y";
echo $z;
---Output---
Hello World
Objects are important too, sorta. Objects are just items of a class, so for example
<?php
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("red", "Volvo");
var_dump($myCar);
?>
The object in this example is $myCar. $myCar belongs to the “Car” class and holds attributes based on it.