Home  >  Article  >  Web Front-end  >  Let’s take a look at the PHP Javascript syntax comparison

Let’s take a look at the PHP Javascript syntax comparison

coldplay.xixi
coldplay.xixiforward
2021-01-11 09:51:401453browse

Let’s take a look at the PHP Javascript syntax comparison

Related free learning recommendations: javascript (Video )

PHP, JavaScript syntax comparison and quick check

Let’s take a look at the PHP Javascript syntax comparison

Full stack engineers come here and learn There are many computer languages, and functions in different languages ​​are often confused. As a full-stack PHPer, the syntax of PHP and JavaScript is often unclear. I need to search on Baidu and check the manual to find the Internet speed. Why not bookmark this article, print it out, and put it aside for quick reference.

Some array map functions in JavaScript are implemented by jQuery. After ES6, official implementations were released. PHP's array and string related functions are named randomly, making it easier to confuse these three.

Coding style

Language PHP JavaScript
Newline ;

#; numbers are not required

Case sensitivityStrict modedeclare(strict_types=1); (PHP7 new feature)Variable declarationPHPConstantlocal variableGlobal variables
Only variable names are case-sensitive Variable names and function names , class names, etc. are all case-sensitive
"use strict" ; (Introduced in ECMAScript 5)
Language
JavaScript
const VAR_NAME = 12;
define('VAR_NAME' , 12);
const MY_FAV = 7; (standard introduced by ES6)
$varName = 12; (PHP strict Generally speaking, there is only function scope, or global scope) function myFunc() {
var varName = 3;
if (true) {
let varName2 = 2;
}
}
(Var must be declared in the function scope, otherwise the variable is globally accessible.)
( The variables modified by let are block-level scope, introduced in ES6)
$varName = 12;
function myFunc() {
global $varName;
}
(When using global variables within the function, you must use global variables to declare external global variables)### ###var varName1 = 3;
varName2 = 2;
function myFunc() {
varName3 = 6;
} (Written here as varName1 , 2, 3 are all global variables)############Global symbol table######$GLOBALS array######window object######### ### is a defined variable######null######undefined############

Variable conversion

Language PHP JavaScript
Convert to bool, boolean $bar = (boolean) $foo;
$bar = (bool) $foo;
$ bar = boolval($foo);
boolVal = Boolean('')
Convert to int $bar = (int) $foo;
$bar = (integer) $foo;
$bar = intval($foo);
intVal = Number("314")
intVal = parseInt("3.14")
convert to float $bar = (float) $foo;
$bar = (double) $ foo;
$bar = (real) $foo;
$bar = floatval($foo);
floatVal = Number("3.14")
flotaVal = parseFloat("12")
Convert to string $bar = (string) $foo;
$bar = strval ($foo);
str = String(123)
str = (123).toString()
Convert to array $arr ​​= (array) new stdClass(); (requires multiple lines of functions to complete)
Convert to object $obj = (object) array('1' => 'foo'); let arr = ['yellow', 'white', 'black'];
let obj = { ...arr}
Time stamp to date $date = new DateTime();
$date->setTimestamp(1171502725) ;
var date = new Date(1398250549490);
Character to date $dateObj = new DateTime($dateStr); var myDateObj = new Date(Date.parse(datetimeStr))
Convert to empty (unset) $var; \ will not delete the variable or unset its value. Just return NULL value
Get the type $varType = gettype($var); varType = typeof myCar
Class judgment $boolRe = $a instanceof MyClass; boolRe = a instanceof MyClass
new Date().constructor === Date

Operator

Language PHP JavaScript
Ternary (ternary) operation $a = $a ? $ a : 1;//The first type
$a = $a ? : 1;//The second type PHP5.3 supports
re = isMember ? 2.0 : '$10.00'
Coalescing operator $a = $a ?? 1; // PHP7 supports

Array

##var mycars = new Array("Saab","Volvo","BMW")
Language PHP JavaScript
Basic $a=array(0 => 1, 1 => 2,4,5,6);
$array = [ "foo" => "bar", "bar" => "foo"]; // PHP 7 syntax
b = [1,2,3]
Append $arr ​​= array();
$arr[key1] = value1;
$arr[key2] = value2;
var mycars=new Array()
mycars[0]="Saab"
mycars[1]="Volvo"
mycars[2]=" BMW"
new

Loop

LanguagePHPJavaScript for loopfor ($i=1; $i {< ;br/> echo $i ;
}
for (var i=0; i {
document.write(cars[i]);
}##foreach, for in loop##while loopwhile($i {
echo $i ;
$i ;
}while (i{
x=x "The number is " i "do while loopdo {
$i ;
echo $i;
} while ($ido
{
document.write(i);
i ;
}
while ( i

This article comes from

Array function

$x= array("one","two","three");
foreach ($x as $value)
{
echo $value;
}
var person= {fname:"John",lname:"Doe",age:25};
for (x in person) // x is the attribute name {
txt=txt person[x];
}
";
i ;
}

##each functionfunction map_Spanish($n)
{
echo $n;
$b = array("uno", "dos", "tres", "cuatro", "cinco");
$c = array_map("show_Spanish", $ a);$.each([ 52, 97 ], function( index, value ) {
alert( index ": " value );
});
jQuery way
const items = ['item1', 'item2', 'item3'];
items.forEach(function(item, index, arr){
console.log('key:' index ' value:' item);
});
(Introduced in ES6)The callback function iteratively reduces the array to a single valuefunction sum($carry, $item) {
$carry = $item;
return $ carry;
}
$a = array(1, 2, 3, 4, 5);
var_dump(array_reduce($a, "sum")); // int(15)var numbers = [65, 44, 12, 4];
function getSum(total, num) {
return total num;< ;br/>}
console.log(numbers.reduce(getSum));
Starting with ECMAScript 3Filtering with callback functions Cells in the arrayfunction odd($var) {
// returns whether the input integer is odd
return($var & 1);
$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=> ;5);
echo "Odd :\n";
print_r(array_filter($array1, "odd"));function isBigEnough(element) {< ;br/> return element >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); \Introduced in JavaScript 1.6
Language PHP JavaScript
Get the number of elements in the array count($arr); arrayObject.length
Splicing two strings array_merge($arr1, $arr2); arr1.concat(arr2)
Delete array elements unset($arr[$key]); delete arr1[key]
Splice the array into a string implode(',', $arr1); arr.join(',')
Delete and return the last element of the array $re = array_pop($arr1); re = arrayObject.pop()
Add an element to the end of the array array_push ($arr1, $var1); len = arrayObject.push(newele1)
Delete the first element of the array and return $re = array_shift($arr1); re = arrayObject.shift()
Add one or more elements to the beginning of the array array_unshift($arr1, $var1); len = arrayObject.unshift(newele1)
Return the selected element from the existing array $newArr = array_splice($arr1,$start,$len); newArr = arrayObject.slice(start,end)
Sort sort($arr1); arrayObject.sort(sortByFunc = null)
Reverse the order of elements in the array array_reverse(&$ arr, $keepKeys = true); arrayObject.reverse()



Characters

LanguagePHP JavaScriptCreate$str = "a string";
\\\\What is special is that PHP Variables can be parsed within double quote characters
$str2 = 'tow string';var carname = "Volvo XC60";
var carname = 'Volvo XC60';< ;br/> (Similarly, escape characters can be used in double quotes)Multi-line characters$bar = foo
bar
EOT;
var tmpl ='
!!! 5
html< ;br/> include header
body
include script'##character splicing

String functions

$str1 . $str2 str1 str2
Language PHP JavaScript
Get the character length strlen($str); string.length
Get the substring substr ( string $string , int $start [, int $length ] ) : string string.substr(start,length)
str.slice(1, 5);
Use one string to split another string $pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
var str="How are you doing today?";
var n=str.split(" ");
\ output:How,are,you,doing,today?
Remove whitespace characters at the beginning and end of the string (or other characters) trim ( string $str [, string $character_mask = " tnr0x0B" ] ) : string
(PHP functions are more customizable)
var str = " string ";
alert(str.trim());
Find the first occurrence of a string $mystring = 'abcsdfdsa';
$pos = strpos($mystring, 'cs');
var str="Hello world, welcome to the universe.";
var n=str.indexOf("welcome");
Convert the string to lowercase strtolower ( string $string ) : string string .toLowerCase()
Convert the string to uppercase strtoupper ( string $string ) : string string.toUpperCase()

Object

##regular
Language PHP JavaScript
Empty object $obj = new stdClass(); var obj = new Object(); // Or
person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};
Object properties $obj = new stdClass();
$obj->a = 12;
var myCar = new Object();
myCar.year = 1969 ; // js can also delete attributes in the form of array
myCar["year"] = 1969;
unset($obj-> ;a); delete object.property
delete object['property']

LanguagePHPJavaScriptCreate regular expression Formula$pattern = "/.*/i";var re = /ab c/;int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] ) ereg ( string $pattern , string $string [, array &$regs ] ) : intMathematical function
##PCRE Regular
var myRe = /d(b ) d/g;
var myRe = new RegExp("d(b )d", "g");
POSIX Regular
(None)

LanguagePHPRandom function $re = mt_rand($min, $max); // Returns a random integer between min ~ max pow(x,y)Others
JavaScript
Math.random() // Returns a random number between 0 ~ 1 Number x raised to the yth power
Math.pow(x,y)

LanguagePHP##Expand, variable functionfunction add(...$numbers) {
foreach ($numbers as $n) { $sum = $n; }} $my_array = array('a'=>'Dog','b'=>'Cat','c'=>'Horse');
list($a, $ b, $c) = $my_array;
//php5, if the php7 version supports the following syntax
['a'=>$a, 'c'=>$c] = $my_array ;var date1 = [1970, 2, 1]; var date2 = {year: 1980, mouth: 3, day: 21}; console.log(date1);
JavaScript
echo add(1, 2, 3, 4); // PHP5.6 starts to support function myFunction(x, y , z) { }
var args = [0, 1, 2];
myFunction(...args); (ES6 starts to support)

Destructuring
[ year, mouth ]= date1; ({ mouth } = date2); console.log(year);
console.log(mouth);




Welcome to collect it. If you think you need to add anything, please leave a message.

The above is the detailed content of Let’s take a look at the PHP Javascript syntax comparison. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete
Previous article:How to loop map in reactNext article:How to loop map in react