Table of Contents
Variable declaration" >Variable declaration
Magic Variable" >Magic Variable
##array" >##array
Array function" >Array function
" >##String function
Object" >Object
##Regular" >##Regular
Home Backend Development PHP Tutorial Full stack engineers come here! PHP Javascript syntax comparison and quick check

Full stack engineers come here! PHP Javascript syntax comparison and quick check

Aug 25, 2020 pm 05:22 PM
javascript php Getting started with php php tutorial grammar

#Qp, JavaScript gram -comparison, speed check

all to see that there are more computer languages ​​to learn, often mixing various functions of different languages. 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.

Related recommendations: "PHP Video Tutorial" "javascript Advanced Tutorial"

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

Coding style

##Line breakNewlineCase sensitivityOnly variable names are case-sensitiveVariable names, function names, class names, etc. are all case-sensitiveStrict modedeclare( strict_types=1); (new feature of PHP7)"use strict";(introduced in ECMAScript 5)
Language PHP JavaScript
; is required, \n is not required \n, and ; are not required, except for(;;)
LanguagePHPJavaScriptConstantconst VAR_NAME = 12; const MY_FAV = 7; (standard introduced in ES6) Local variables$varName = 12; (PHP only has function scope and global scope)function myFunc() { Global variables$varName = 12; var varName1 = 3; Global symbol table$GLOBALS arraywindow object (html environment) is a defined variablenullundefined

Variable conversion

define('VAR_NAME', 12);
var varName = 3;
if (true) {
let varName2 = 2;
}
}
(Var must be declared within the function scope, otherwise the variable is globally accessible.)
(The variable modified by let is block level Scope, introduced in ES6)

function myFunc() {
global $varName;
}
(To use global variables within a function, you must use global variables to declare external global variables)
varName2 = 2;
function myFunc() {
varName3 = 6;
} (Writing here varName1, 2, and 3 are all global variables)
global object (nodejs environment)
##Convert to string$bar = (string) $foo; str = String(123) Convert to array$arr ​​= (array) new stdClass();(requires multi-line function to complete)Convert to object$obj = (object) array('1' => 'foo');let arr = ['yellow', 'white ', 'black']; Convert timestamp to date$date = new DateTime(); var date = new Date(1398250549490);Character to date$dateObj = new DateTime($dateStr);var myDateObj = new Date(Date.parse(datetimeStr))convert to empty(unset) $ var; \ does not delete the variable or unset its value. Just return NULL valueGet the type$varType = gettype($var); varType = typeof myCarClass judgment$boolRe = $a instanceof MyClass;boolRe = a instanceof MyClass
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”)
floataVal = parseFloat(“12”)
$bar = strval($foo);
str = (123).toString()
let obj = {...arr}
$date->setTimestamp(1171502725);

new Date() .constructor === Date
LanguagePHPJavaScriptCurrent file$filePath = __FILE__;filePath = __filenameCurrent directory$currentDir = __DIR__;curDir = __dirnameCurrent line of code__LINE__Current function__FUNCTION__Current class__CLASS__##Current namespace

Operators




__NAMESPACE__
Language PHP JavaScript
Ternary (ternary) operation $a = $a ? $a : 1;//The first type
$a = $a ? : 1; //The second type of PHP5.3 supports
re = isMember ? 2.0 : '$10.00'
merge operator $a = $a ?? 1; // PHP7 supports
LanguagePHPJavaScript##Basic $array = [ “foo” => “bar”, “bar” => “foo”]; // PHP 7 SyntaxAppend $arr[key1] = value1; mycars[0]=”Saab”new##loop
$a=array(0 => 1, 1 => 2,4,5,6);
b = [1,2,3]
$arr ​​= array(); $arr[key2] = value2;

var mycars=new Array()
mycars[1]=”Volvo”
mycars[2]=”BMW”

##var mycars = new Array(“Saab”,”Volvo ","BMW")

language PHP##for loopfor ($i=1; $i<=5; $i ) { echo $i ; foreach ($x as $value) { echo $value; }var person= {fname:”John”,lname:”Doe”,age:25 }; $i ; }x=x “num is “ i ;##do while loop} while ( $ i<= 5);do { i ;
JavaScript
}
for (var i=0; i < cars.length ; i )
{
document.write (cars[i]);
}

##foreach, for in loop

$x=array(“one”,”two”,”three” );
for (x in person) {
txt=txt person[x];
}
##while loop

while ($ i <= 5) {
echo $i ;
while (i<5) { i ;
}


do {
$i ;
echo $i;
console.log(i); } while (i < 5);


##Splice two Stringarray_merge($arr1, $arr2);arr1.concat(arr2)Delete array elementsunset($arr[$key]);delete arr1[key]Splice the array into a stringimplode(', ', $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 arrayarray_push($arr1, $var1); len = arrayObject.push(newele1)Delete the first element of the array and return it$re = array_shift($arr1) ;re = arrayObject.shift()Add one or more elements to the beginning of the arrayarray_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)Sortsort($arr1); arrayObject.sort(sortByFunc = null)Reverse the order of elements in the arrayarray_reverse(&$arr, $keepKeys = true); arrayObject.reverse()##each function{alert( index “: “ value );The callback function iteratively reduces the array to a single value $carry = $item;function getSum(total, num) {Use callback function to filter cells in array // returns whether the input integer is odd
LanguagePHPJavaScript
Get the number of elements in the arraycount($arr);arrayObject.length



function map_Spanish($n) echo $n;
}
$b = array(“uno”, “dos” , "tres", "cuatro", "cinco");
$c = array_map("show_Spanish", $a);

$.each([ 52, 97 ], function( index, value ) {
});
// ↑ This is the jQuery way
const items = ['item1', 'item2', 'item3'] ;
items.forEach(function(item, index, arr){
console.log('key:' index ' value:' item);
});
(Introduced in ES6)

function sum($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];
return total num;
}
console.log(numbers.reduce (getSum));
Started from ECMAScript 3

function odd($var) { return($var & 1);
}
$array1 = array(“a”=>1, “b”=>2, “c”= >3, “d”=>4, “e”=>5);
echo “Odd :\n”;
array_filter($array1, “odd”);

function isBigEnough(element) { return element >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); \\ JavaScript 1.6 introduced

characters

##character splicing$str1 . $str2str1 str2
Language PHP JavaScript
Create $str = "a string";
\\What's special is that PHP can parse variables in double quote characters
$str2 = 'tow string';
var carname = "Volvo XC60";
var carname = 'Volvo XC60';
(Similarly, escape characters can be used in double quotes)
Multi-line characters $bar = << foo
bar
EOT;
var tmpl ='\
!!! 5\
html \
include header\
body\
include script'
##LanguagePHPJavaScriptGet the character lengthstrlen($str);string.lengthGet substringsubstr ( string $string , int $start [, int $length ] ): stringstring.substr(start,length ) Use one string to split another string$pizza = “piece1 piece2 piece3 piece4 piece5 piece6 ”;echo $pieces[0]; // piece1\ 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 = “ \t\n\r\0\x0B” ] ) : string Find the first occurrence of a string$mystring = 'abcsdfdsa'; Convert the string to lowercasestrtolower ( string $string ): stringstring.toLowerCase()Convert the string to uppercasestrtoupper ( string $string ) : stringstring.toUpperCase()##Function
str.slice(1,5);
$pieces = explode(“ “, $pizza);
var str=”How are you doing today?”;
var n=str.split(“ “);


(PHP functions are more customizable)var str = “ string “;
alert(str.trim());

$pos = strpos($mystring, 'cs');var str="Hello world, welcome to the universe.";
var n=str.indexOf ("welcome");

LanguagePHPFunction parameters$argv = func_get_args (void);
JavaScript
var argv = arguments \\ Direct object within a function
LanguagePHPJavaScript
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 be in array form
myCar["year"] = 1969;
Delete property unset($obj->a); delete object.property
delete object[' property']
##LanguageCreate regular expressionPCRE Regular var myRe = new RegExp(“d(b )d”, “g” );POSIX regular
PHP JavaScript
$pattern = “/.*/i”; var re = /ab c/;
int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] ) var myRe = /d(b )d/g;
ereg ( string $pattern , string $string [, array &$regs ] ) : int (none)

Mathematical functions

##LanguagePHPJavaScriptRandom function$re = mt_rand($min, $max); // Returns the value between min~max Random integerMath.random() // Returns a random number between 0 ~ 1x raised to the yth powerpow(x ,y)Math.pow(x,y)##Package, space

LanguagePHP##Namespacenamespace MySpace; (None)Introduce packageuse Package; use Package as Package1, Package2; import “my-module”; include 'b.php'; require 'bc.php';< ;script type='text/javascript' src='b.js'>
JavaScript
const http = require('http') (CommonJS specification) import {foo as fo, bar} from “my-module”;
(es6 implementation, import requires and export Use together)


Introduce files
(only used in html)
<h2> <span class="header-link octicon octicon-link"></span>Others</h2> <table> <thead><tr class="firstRow"> <th style="border-color: rgb(221, 221, 221);">Language</th> <th style="border-color: rgb(221, 221, 221);">PHP</th> <th style="border-color: rgb(221, 221, 221);">JavaScript</th> </tr></thead> <tbody> <tr> <td style="border-color: rgb(221, 221, 221);">Expand, variable function</td> <td style="border-color: rgb(221, 221, 221);">function add(...$numbers) { <br> foreach ($numbers as $n) { <br> $sum = $n; <br> }<br>} <br>echo add(1, 2, 3, 4); // PHP5.6 starts to support </td> <td style="border-color: rgb(221, 221, 221);">function myFunction(x, y, z) { } <br> var args = [0, 1, 2]; <br> myFunction(…args); (supported from ES6) </td> </tr> <tr> <td style="border-color: rgb(221, 221, 221);">Destructuring</td> <td style="border-color: rgb(221, 221, 221);">$my_array = array('a' =>'Dog','b'=>'Cat','c'=>'Horse'); <br> list($a, $b, $c) = $my_array; <br>/ /php5, if the php7 version supports the following syntax<br> ['a'=>$a, 'c'=>$c] = $my_array;</td> <td style="border-color: rgb(221, 221, 221);">var date1 = [1970, 2, 1];<br>[ year, mouth ]= date1;<br>var date2 = {year: 1980, mouth: 3, day: 21};<br>({ mouth } = date2);<br>console. log(date1);<br>console.log(year);<br>console.log(mouth);</td> </tr> </tbody> </table> <p>Welcome to collect it, if you think it needs to be added place, please leave a message. </p>

The above is the detailed content of Full stack engineers come here! PHP Javascript syntax comparison and quick check. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles