Exploring the differences between PHP and Python…
- Assignment operator
$foo = 'bar';
vsfoo = 'bar'
- Create an empty array
$foo = [];
vs empty listfoo = []
- Create an array with values
$foo = [1, 2, 'str'];
vs list with valuesfoo = [1, 2, 'str']
- Max value of array
max($arr)
vsmax(arr)
- Min value of array
min($arr)
vsmin(arr)
- Modulo
$a % $b
vsa % b
- Return statement
return $result;
vsreturn result
-
Convert a string to an array.
- Chunk size is 1.
$chunks = str_split($str)
vschunks = list(str)
- Chunk size is N.
$chunks = str_split($str, $n)
vschunks = [str[i:i+n] for i in range(0, len(str), n)]
- Chunk size is 1.
-
Convert variable to int
intval('5')
vsint('5')
-
Convert variable to string
strval(5)
vsstr(5)
-
Check if value exists in array
in_array(2, [1, 2, 3])
vs2 in [1, 2, 3]
-
Check if the value and type of the operands is the same
$a === $b
vsa == b
-
Filter array values by condition
array_filter([1, 2, 'foo'], 'is_int');
vs[e for e in [1, 2, 'foo'] if isinstance(e, int)]
-
Function declaration
function foo(){ }
vsdef foo():
-
Join array elements with a string
implode(',', $arr)
vs','.join(arr)
-
Map callback to the elements of the array
array_map('intval', $arr)
vsmap(int, arr)
-
Search element in array and get their index
array_search(1, [1, 2, 3])
vs[1, 2, 3].index(2)
-
Split a string by a string (return array):
explode(',', $str)
vsstr.split(',')
-
Split a string by a string with limit:
explode(',', $str, 3)
vsstr.split(',', 3)
-
Reverse a string
$str = strrev($str)
vsstr = str[::-1]
-
Round fractions up and down:
- In PHP:
ceil(1.5); // → 2 floor(1.5); // → 1
- In Python:
import math math.ceil(1.5) # → 2 math.floor(1.5) # → 1
-
Ternary conditional operator
$condition ? $a : $b
vsa if condition else b
-
Iterate over array
foreach($arr as $value)
vsfor value in arr:
-
Iterate over array with index
foreach($arr as $index => $value)
vsfor index, x in enumerate(arr):
-
Iterate over associative array with index:
- In PHP:
foreach($arr as $key => $value){ echo $key . '->' . $value; }
- In Python (dictionaries):
for key in a_dict: print(key, '->', a_dict[key])
- pass - a placeholder for future code