Skip to main content

PHP vs Python Syntax Comparison

PHP: Variable Declaration
$name = "Alice";
$age = 30;
Python: Variable Declaration
name = "Alice"
age = 30
PHP: Output
echo "Hello";
Python: Output
print("Hello")
PHP: Return
function getValue() {
  return 5;
}
Python: Return
def get_value():
  return 5
PHP: Assignment in If
if ($x = $y) { ... }
Python: Assignment in If
if (x := y): ...
PHP: Not Empty
if (!empty($x)) { ... }
Python: Not Empty
if x:
  ...
PHP: Concatenate
$greeting = "Hi " . $name;
Python: Concatenate
greeting = "Hi " + name
PHP: foreach
foreach ($arr as $x) {
  echo $x;
}
Python: for loop
for x in arr:
  print(x)
PHP: while loop
$i = 0;
while ($i < 5) {
  $i++;
}
Python: while loop
i = 0
while i < 5:
  i += 1
PHP: Multiply
$total = $x * $y;
Python: Multiply
total = x * y
PHP: Indexed Array
$colors = ["red", "green"];
echo $colors[1];
Python: List
colors = ["red", "green"]
print(colors[1])
PHP: Echo Object List
$users = [
  [ "id" => 1, "name" => "Alice" ],
  [ "id" => 2, "name" => "Bob" ]
];

foreach ($users as $user) {
  echo $user["name"] . "<br>";
}
Python: Print Object List
users = [
  { "id": 1, "name": "Alice" },
  { "id": 2, "name": "Bob" }
]

for user in users:
  print(user["name"])
PHP: Assoc Array
$user = [
  "name" => "Alice"
];
echo $user["name"];
Python: Dictionary
user = {
  "name": "Alice"
}
print(user["name"])
PHP: Value in Array
$colors = ["red", "green", "blue"];

if (in_array("green", $colors)) {
  echo "Found!";
}
Python: Value in List
colors = ["red", "green", "blue"]

if "green" in colors:
  print("Found!")
PHP: Count
count($colors)
Python: Length
len(colors)