Data type in php:
There are seven data types in php:
//1.String string, a character wrapped in quotation marks, such as: $str = 'hello word'; //2.Integer integer, which can be positive or negative, has decimal, hexadecimal and octal, and cannot have decimal point, space, comma and other symbols, such as: $num = 123; //3.Float floating point type refers to the number with decimal part or exponential form, such as: $num = 5.2; $num2 = 2e; //4.Boolean, the value is true or false, such as: $bool = false; //5.Array. There are three types of arrays in php: numeric array, associative array and multidimensional array, such as: $arr = array(1,'2','false');//Numeric array, i.e. common array $arr = array("name"="jack","age"=18);//Associative array, an array with a specified key $arr = array(1,2,array(3,4));//Multidimensional array, an array containing one or more arrays //6.Object object. Objects in php use the class keyword to declare class objects. Classes can contain attributes and methods, such as: class Person{ // Properties: $name = 'jack'; $age; // Construction method: function __construct($ages){ $this->age=$ages; } // method: function say(){ echo "{$this->name}---- {$this->age}"; } } $per=new Person(20); $per->say(); //7.NULL indicates that there is no value, such as: $nulls = null;
Array sorting:
php provides several methods to sort arrays according to numbers or letters, such as:
//sort(arr); Ascending sort //rsort(arr); Descending sort //asort(arr); Sort in ascending order according to the value of the associative array //ksort(arr); Sort in ascending order according to the key of the associative array //arsort(arr); Sort in descending order according to the value of the associative array //krsort(arr); Sort in descending order according to the keys of the associative array
Circular statements in php:
php provides while, do while, for and foreach loops, as follows:
//While (condition) {code block}: execute the code block when the condition is true, such as: while($num == 1){echo true;} //do {code block} while (condition): execute the code block at least once, and judge whether to continue executing the code block through conditions, such as do{echo 'hello';}while($str == 'hello'); //For (initial value, condition, increment) {code block}: execute the code block according to whether the initial value meets the conditions; If not, execute the incremental judgment condition. Whether to execute the code block in sequence, such as: for($i = 0;$i < 5;$i++){echo i;}; //foreache($arr as $value) {code block;}, foreach is used to traverse the array. When it is an ordinary array, $value is the array element; When it is an associative array, $value is an item in the array. To get a specific value, you need to add a subscript; Alternatively, you can receive data with two parameters, one of which is the key. The other is a value, such as foreach($arr as $value){echo $value;} foreach($arr as $data){echo $data[id];} foreach($arr as $key => $value){echo $key . '---' . $value;}
Mixed compilation in php:
Comments in php://
//Ordinary embedded php code: <p><?php echo 'hello'; ?></p> //Statement mix: <?php if ($age>18){ ?> <p>adult</p> <?php }else{ ?> <p>under age</p> <?php } ?> <?php if($age > 18): ?> <p>adult</p> <?php else: ?> <p>under age</p> <?php endif ?> //Directive statement: <?php if(true): echo 'hello'; endif; if(true): each 'hello' else: each 'word' endif; ?>
php local file operation process:
//1.php provides a method to read the file, which will return the file content as a string $str = file_get_contents('file URL'); //2.php provides a method to parse a string, explode("delimiter", string), which returns the parsed string in the form of an array. It should be noted that the transfer character should use double quotation marks, otherwise the parsing fails $arrData = explode("\n",str); //3. Print out the data in the array by loop: foreach($arrData as $data){ var_dump($data); };
Common API s in php:
API: application programming interface. All interfaces are physical objects that provide a specific ability. They are characterized by input and output. The interface used in development is called API. Any programming language itself does not have much capability, most of which comes from API. php has 1000 + built-in functions. Not every function can be called directly. Some need to install or call additional plug-in extensions.
method | describe |
---|---|
strtolower(str) | Convert string str to lowercase |
trim(str) | Remove the spaces at both ends of the string; Remove the space on the left of the string: ltrim('str '); Remove the blank space on the right side of the string: rtrim('hello ') |
substr(str,index) | Intercepting from the index bit of the string str and returning the intercepted string; Intercept wide character set: mb_substr('original string ', intercepted length) |
print_r() | Output the value and VaR of each item of the array_ Dump() is similar |
strtoupper(str) | Replace str with capital letters |
strpos(str,s) | Find the character s appearing for the first time in the string str and return the position of S; Wide character lookup mb_strpos('original string ',' part to find ') |
str_replace(targstr,repstr,str) | Replace the string by replacing targstr in str with repstr |
str_repeat(str,n) | Repeat the string, repeating the character str n times |
explode('\n','str') | Split string str with \ n |
array_keys(arr) or array_value(arr) | Gets the key or value in the associative array arr |
array_key_exists('key',arr) | Judge whether there is a key in the arr array, and return a Boolean value |
array_unique(arr) | Remove duplicate elements from array arr |
array_push(arr,ele1,ele2,...) | Append one or more elements to the arr array |
array_pop(arr) | Delete the last element in array arr |
count(arr) | Returns the length of array arr |
in_array(ele,arr,boolean) | Detect whether there is an ele element in the array arr, and return 1 if it exists, otherwise nothing will be returned; Parameter 3 is a Boolean value. When true, it means that the data type of finding ele is consistent with that of detecting array arr |
array_search(ele,arr) | Returns the key (subscript) of element ele in array arr |
time() | The returned value is the second value from 1970 / 1 / 1 to the present, which has the same meaning as the millisecond value in js, but here is the second number, and the base between them is 1000 |
Date (time format, timestamp) | Format a timestamp, which returns Greenwich mean time, which is 8 hours less than the time in the East eighth district. In order that this time is the time of the people's Republic of China, you can write the code: date_default_timezone_set('prc ') or configure PHP Date in INI file timezone = PRC |
Strtotime (time string) | Format the existing time string |
basename(url,php) | Returns the file name part of the url path. The second parameter is optional, indicating the file extension |
dirname() | Returns the part of the path except the file name |
copy() | Copy file |
strlen(str) and mb_strlen('wide character set ') | Get the length of str string. Chinese belongs to the wide character set, and each word accounts for three characters. strlen() can only get the length of Latin characters. php has specially added a set of APIs to the wide character set - all APIs are mb_xxx |
phpinfo() | API for printing php information |
uniqid() | Returns a non repeating number at random |
json_decode(json,true) | Parsing json format strings into associative arrays |
json_encode(arr) | Replace the associative array arr with json format string |
file_put_contents('test.json',jsonstr) | Replace the string in json format with test json file |
header() | Set the file response header, which can handle web page redirection, response file format, etc. it is commonly used for web page redirection and file download |
array_splice(arr,index,length) | Delete the element with the starting length of index in array arr |
pathinfo(path,options) | Return the path in the form of an array. options has four keyword parameters, which are used to return a part of the specific path. For details, please refer to the official document |
list(el1,el2...)=[arr1,arr2...] | Receive each element of the corresponding position in the array, which is often used to calculate the age when the birthday is known |
unset(data) | Delete data |
<?php // Process string tests: echo substr('qwe today rt',1);//we today rt echo mb_substr('Go to the amusement park today',2);//To go to the amusement park, you need to configure PHP Extended wide character set in ini echo strtolower('qweqQFQW');//qweqqfqw echo strtoupper('sfaasfEFE');//SFAASFEFE echo trim(' today ee good ');//How are you today echo ltrim(' jigage');//jigage echo rtrim(' jin ');//jin echo strpos('werqr','q');//3 echo str_replace('123','abc','1234');//abc4 echo str_repeat('☆',5);//☆☆☆☆☆ echo strlen('hello');//5 echo mb_strlen('Hello');//2 $str='hello world,taday is a beautiful day'; print_r(explode(' ',$str));//Array ( [0] => hello [1] => world,it [2] => is [3] => a [4] => beautiful [5] => day ) // Processing array tests: $arr = array( 'key1'=>'value1', 'key2'=>'value2', 'key3'=>'value3', ); print_r(array_keys($arr));//Array ( [0] => key1 [1] => key2 [2] => key3 ) print_r(array_values($arr));//Array ( [0] => value1 [1] => value2 [2] => value3 ) var_dump(array_key_exists('key1',$arr));//bool(true) $arr=array( '1', '2', '1', '4' ); var_dump($arr);//array(4) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "1" [3]=> string(1) "4" } $arra=array_unique($arr); print_r($arra);//Array ( [0] => 1 [1] => 2 [3] => 4 ) array_push($arr,3,5,6); print_r($arr);//Array ( [0] => 1 [1] => 2 [2] => 1 [3] => 4 [4] => 3 [5] => 5 [6] => 6 ) array_pop($arr); var_dump($arr);//array(3) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "1" } echo count($arr);//4 echo in_array('4',$arr);//1 echo array_search('4',$arr);//3 // Processing time test: echo time();//1594333103 date_default_timezone_set('PRC'); echo date('Y-m-d H:i:s'); $time='2019-9-9 21:23:32'; $datetime=strtotime($time); echo date('Y year m month d day<b\r>H:i:s',$datetime);//\ in < B \ r > is a translation character because R is a special character in date // Processing path test: $path = 'E:/web front end/web Front end exercise/5.php practice/19.String common API/19.String common API.php'; echo basename($path)//19. String common API php ?>
Create function:
Functions in php are basically the same as those in other languages. Function names should start with letters or underscores. Function names can have numbers, such as:
//Simple functions: function hello(){echo 'hello';}; //For the function passing in parameters, the parameters can be multiple, separated by commas, such as: function sum($a,$b){echo $a + $b;} //Function with return value: function getHello(){return 'hello';}
Magic constant:
The so-called magic constants in php mean that the results of constants are different in different positions, and their writing is not case sensitive. There are eight constants in php, as follows:
//1.__LINE__ Returns the number of lines of the current code. This constant is placed in different code lines and returns different code lines, such as: echo __LINE__;//2 //2.__FILE__ Returns the absolute path and file name of the current file, such as: echo __FILE__;//For example: F: \ test \ index php //3.__DIR__ Returns the absolute path of the current file, such as: echo __DIR__;//For example: F:\test //4.__FUNCTION__ Returns the function name of the current function. The function name is case sensitive, such as: function myFn(){echo __FUNCTION__;}; myFn();//myFn //5.__CLASS__ Returns the name of the current class, such as: class person {function ech(){echo __CLASS__;}}; $per = new person(); $per->ech();//person //6.__TRAIT__ To realize code reuse, php is a single inheritance language (a subclass can only have one parent class), but multiple inheritance can be realized through trait, which is similar to that of classes. For example: trait cat {//Trait declaration: generally, only methods are added in trait, and an object cannot be instantiated. Trait can nest trait, function eat(){echo 'eat';}; }; trait monkey{ function run{echo 'run';} }; trait dog { use monkey;//Nested using trait function wo(){echo 'Flourishing';}; function eat(){echo 'eat meat';}; }; calss Animal{ use cat,dog;//Use trait. Use the use keyword when using trait. If you want to use multiple traits, separate them with commas //use cat,dog {when multiple trait s are used and there are methods with the same name, you can add {} after them and replace them with insteadof in parentheses: //cat::eat insteadof dog; Replace the eat method in cat with that in dog //dog::eat as dogeat; Or alias the eat method in dog //} }; $animals = new Animal(); $animals->eat();//eat $animals->run();//run //7.___METHOD__ Returns the function name and the name of the method definition, such as: function fntest(){echo __METHOD__;}; fntest();//fntest //8.__NAMESPACE__ Returns the name of the current namespace, such as: namespace mydemo; echo __NAMESPACE__;//mydemo
Tip: the pictures and other materials in this article come from the Internet. If there is infringement, please send an email to: 810665436@qq.com Contact the author to delete.
Author: Kuhai