PHP_ Basics, PHP Basics _php Tutorials

Source: Internet
Author: User

PHP_ Basics, PHP basics


Directory

    • Array

    • Function

    • Classes and objects

    • String manipulation

    • Session control

    • Time and date

    • Exception handling

One, array

  1. Indexed array

Header("content-type:text/html; Charset=utf-8 ");//create an empty array$str=Array();//indexed array: The key of an array is an array of integers, and the integer order of the keys starts at 0, and so on. $fruit=Array("Apple", "banana", "pineapple");//Indexed array Assignment://1. Assign a value with the name of the array variable followed by a bracket$arr[0]= ' Apple ';//Use the-= symbol to separate keys and values, the left for the key, and the right for the value. Array(' 0 ' = ' apple ');//count ($arr) returns the array length//for iterating through the values in the indexed array for($i= 0;$i<Count($fruit);$i++){    Echo"$fruit[$i]
";}//foreach iterates through the values in an indexed arrayforeach($fruit as $k=$v){ Echo $k." ...".$v."
";}

2. Associative arrays

Header ("content-type:text/html; Charset=utf-8 "); // associative array: The key of an exponential group is an array of strings $fruit Array (' apple ' = ' apple ', ' banana ' and ' banana ', ' pineapple ' and ' pineapple '); // Associative array assignment//1. Assign a value with the name of the array variable followed by a bracket $arr [' Apple ']= ' Apple '; // 2. Use the-= symbol to separate the keys and values, the left for the key, and the right to indicate the value Array (' apple ' = ' apple '); // The Foreach loop accesses the values in the associative array foreach ($fruitas$k=$v) {    echo '
The English key name of the fruit: '. $k. ', the corresponding value is: '. $v ;}

Second, function

1. Variable functions

// A variable function that invokes a function by its value function name () {    echo ' Jobs ';} $func = ' name '; // calling a mutable function $func

2. Determine if a function exists

function func () {} if (function_exists(' func ')) {    echo ' exists ';}

III. Classes and objects 

//define a classclassCar {//Defining Properties     Public $name= ' car '; //Defining Methods     Public functionGetName () {//You can use the $this pseudo-variable to invoke an object's properties or methods inside a method        return $this-name; }}//instantiate an object$car=NewCar ();//methods for calling objectsEcho $car-getName ();//class//public: Exposed//protected: Protected, protected property does not allow external calls to//private: private, private property does not allow external calls//static methods: Use keyword static modifiers//static methods do not need to instantiate objects , which can be called directly from the class name, and the operator is double-colon:classCar { Public Static functionGetName () {returnCar; }}EchoCar::getname ();//The result is "car"//constructor __construct (): Call this function every time the object is created//destructor __destruct (): Call this function every time the object is destroyedclassCar {//add constructors and destructors    function__construct () {Print"constructor is called \ n"; }    function__destruct () {Print"destructor is called \ n"; }}$car=NewCar ();

Four, string manipulation

  1. The difference between single and double quotes

// String variables directly contained in double quotation marks//the contents of a single quote string are always considered ordinary characters $str= ' Hello '; Echo $str // Run Result: STR is Hello Echo // operation Result: STR is $STR

2. Remove whitespace from the string

// trim removes spaces at both ends of a string. RTrim is to remove a string to the right of the space//ltrim is to remove the left space of a string trim("space");

3. Get the length of a string

// English character length strlen ($str); // Chinese character length mb_strlen ($str, "UTF8");

4. Interception of strings

// The Intercept function of the English string substr ()//substr (string variable, start intercept position, intercept number)$str= ' I love you '; Echo substr ($str, 2, 4); // Chinese string intercept function Mb_substr ()//mb_substr (string variable, start intercept position, intercept number, page encoding)$str= ' I love you, China '; echo mb_substr ($str, 4, 2, ' UTF8 ');

5. String Lookup

// Strpos (string to be processed, string to position, starting position of position [optional]) $str = ' I want to study at IMOOC '; $pos Strpos ($str, ' Imooc ');

6. String substitution

// Str_replace (The string to find, the string to replace, the string to be searched, and the replacement to count [optional]) $str = ' I want to learn JS '; $replace Str_replace $str);

7. Merging and splitting of strings

// string merge function implode (): combines array elements into a single string//implode (delimiter [optional], array) $arr Array (' Hello ', ' world! ' ); $result implode $arr ); Print_r ($result); // The result shows the Hello world!//string-delimited function explode (): The function returns an array of strings consisting of//explode (delimiter [optional], string) $str = ' Apple,banana '; $result Explode $str ); Print_r ($result); // results show Array (' Apple ', ' banana ')

V. Session CONTROL

1.cookie

// setting Cookie//name (cookie name) can be accessed via $_cookie[' name ']//value (the value of the cookie)//expire (Expiration Time) UNIX timestamp format, default is 0, indicating that the browser is off as expired// Path (valid path) if the path is set to '/', the entire site is valid//domain (valid domain) by default the entire domain name is valid, if ' www.imooc.com ' is set, then only valid in www subdomain $value = ' Test '; Setcookie $value ); // valid for one hour Setcookie $value  Time () +3600); // deletion and expiry time of cookies Setcookie  Time ()-1);

2.session

// First Execute Session_Start method to open session Session_Start (); // the session reads and writes through the global variable $_session.  $_session[' name '] = ' jobs '; Echo $_session [' name ']; // Delete a session unset ($_session[' name ']); // Delete all session Session_destroy ();

Vi. Time and date

// UNIX timestamp: Represents the sum of the number of seconds from January 1, 1970 00:00:00 to the current time. The function time () to get the timestamp of the current time of the server $time= times(); Echo $time ; // The date () function, to get the current date//date (timestamp format, specify the timestamp "default is the current date and time, optional")//Set the default time zone date_default_timezone_set (' asia/ Shanghai '); // date of output 1396193923 Echo Date ("y-m-d"); // function Strtotime: Gets the timestamp of a date, or gets the timestamp of a time//strtotime (the time string to parse, the timestamp of the computed return value "default is the current time, optional")// 1398700800, this number represents a 1,398,700,800-second echostrtotimefrom January 1, 1970 00:00:00 through April 29, 2014 (' 2014-04-29 '); // 1398700801, this number represents 1,398,700,801 seconds from January 1, 1970 00:00:00 to 2014-04-29 00:00:01 Echo Strtotime (' 2014-04-29 00:00:01 ');

Vii. Exception Handling

//to create a function that throws an exceptionfunctionChecknum ($number){    if($number>1){        Throw New Exception("Exception hint-number must be less than or equal to 1"); }    return true;}//to trigger an exception in a "Try" code blockTry{checknum (2); //If the exception is thrown, then the following line of code will not be output    Echo' If you can see this hint, your number is less than or equal to 1 ';}Catch(Exception $e){    //Catching exceptions    Echo' Catch exception: '.$e-getMessage ();}//exception has several basic properties and methods, including the following://message exception message content//code exception code//file throws exception file name//line throws exception in the number of rows in the file//the methods commonly used are://gettrace Get exception tracking Information//gettraceasstring get exception tracking information string//getmessage get error messageclassMyExceptionextends Exception {    functionGetInfo () {return' Custom error message '; }}Try {    Throw NewMyException (' ERROR ');} Catch(Exception $e) {    Echo $e-getInfo ();}

http://www.bkjia.com/PHPjc/1093106.html www.bkjia.com true http://www.bkjia.com/PHPjc/1093106.html techarticle Php_ Base, PHP base directory Array function class and object string operation session control time and date exception handling one, array 1, index array header ("content-type:text/html; C ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.