There are many similarities between Python and PHP, but there significant differences:
- PHP variables start with $ signs
- PHP statements must end with a semi-colon
- Instead of indentation, PHP uses pairs of curly brackets { } to enclose blocks of code inside conditional statements and loops.
- Conditions are enclosed in parentheses ( ).
Case Sensitivity
- PHP keywords are not case sensitive (ECHO = echo = Echo)
- PHP variables are case sensitive ($counter != $Counter)
Comments
# A single line comment ''' A multi line comment '''
// A single line comment # Another single line comment /* A multi line comment */
Printing
print(f"Counter = {counter}")
echo "Counter = ".$counter; /* using concatenation */ echo "Counter = $counter"; /* simple variables inside string */
Assignment
counter = 0 password = "xyz" password = 'xyz' MAXSTUDENTS = 20 colours = ["red", "blue", "green"] computerIDs = [""] * 10 computerId[0] = "AHS-210012" fruits = [] fruits.append("Apple")
$counter = 0; $password = "xyz"; define("MAXSTUDENTS", 20); $colours = array("red", "blue", "green"); $computerIDs = array_fill(0, 10, ""); $computerId[0] = "AHS-210012"; $fruits = array(); array_push($fruits, "Apple");
Operators
Arithmetic operators + – * / ** (exponentiation) % (modulus) are same in Python and PHP
total = total + number total += number fullname = forename + " " + surname
$total = $total + $number; $total += $number; $fullname = $forename . " " . $surname;
Predefined Functions
nameLength = len(fullname) dice = random.randint(1,6) noOfFruits = len(fruits)
$nameLength = strlen($fullname); $dice = rand(1,6); $noOfFruits = count($fruits);
Conditional Statements
if guess == number: print("You guessed the number") elif guess < number: print("Your guess is too small") else print("Your guess is too big")
if ($guess == $number) { echo "You guessed the number"; } elseif ($guess < $number) { echo "Your guess is too small"; } else { echo "Your guess is too big"; }
Switch Statements
Python does not have a switch statement. The simplest equivalent is an if..elif..elif..else statement.
switch ($favcolor) { case "red": echo "Your favourite colour is red!"; break; case "blue": echo "Your favourite colour is blue!"; break; case "green": echo "Your favourite colour is green!"; break; default: echo "Your favourite colour is neither red, blue, nor green!"; }
Fixed Loops (by index)
for x in range(10): print(x)
for ($x = 0; $x < 10; $x++) { echo "<p>$x</p>\n"; }
Fixed Loops (by item)
colours = ["red", "blue", "green"] for colour in colours: print(colour)
colours = array("red", "blue", "green"); foreach ($colours as $colour) { echo "<p>$colour</p>\n"; }