PHP variable declaration
$variable = 1;
JS alternative
let variable = 1;
PHP - check if the variable exists
if (isset($variable))
JS alternative
if (typeof variable !== "undefined")
PHP count array elements
$count = count([2, 3, 4]);
JS alternative
let count = [2, 3, 4].length;
PHP count letters in the string
$len = strlen('some string');
JS alternative
let len = 'some string'.length;
PHP absolute value of a given number
$variable = abs(-5);
JS alternative
let variable = Math.abs(-5);
PHP - power of a number
$square = pow(5, 2);
JS alternative
let square = Math.pow(5, 2);
PHP - square root of a number
$square_root = sqrt(16);
JS alternative
let square_root = Math.sqrt(16);
PHP - minimum number
$max = min(2, 3, 4);
JS alternative
let max = Math.min(2, 3, 4);
PHP - maximum number
$max = max([2, 3, 4]);
JS alternative
let max Math.max(...[2, 3, 4])
PHP calculates sum of the array elements
$sum = array_sum([2, 3, 4]);
JS alternative
let sum = 0;
let arr = [1, 2, 3];
for (let value of arr) {
sum += value;
}
Another way to calculate the same
let arr = [1, 2, 3];
let sum = 0;
let len = arr.length;
for (let i = 0; i < len; sum += arr[i++]);
PHP - string position
$pos = strpos('Hello world', 'world');
JS alternative
let pos = 'Hello world'.indexOf('world');
PHP - edit letter in a string
$string[4] = 'X';
JS alternative
string = string.substring(0, 4) + 'X' + string.substring(5);
PHP convert the variable to integer
$variable = intval(5.5);
JS alternative
let variable = parseInt(5.5);
PHP - explode the sentence
$sentence = "Lorem ipsum dolor st amet";
$words = explode(" ", $sentence);
JS alternative
let sentence = "Lorem ipsum dolor st amet";
let words = sentence.split(" ");