Basic operations of php

不言
Release: 2023-03-25 07:46:01
Original
1751 people have browsed it

This article mainly introduces the basic operations of php, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

php basic knowledge

array function

  • count($arr) Calculate the number of elements in the array

  • ##print_r($arr) Print the array

  • Iterate array

    • for index traversal

    • foreach() iterate array

    • foreach(

      item){} Traverse the values ​​of the array

    • foreach (

      ##key=>$value) Traverse the keys and values ​​of the array

    Array sorting
    • sort(); Sequential sorting will clear the index rsort(); Reverse sorting
    • asort() ; Sorting by value is not clear, index arsort() ;
    • ##ksort(); Sorting by index is not clear, index krsort();
    • ##shuffle ();Random sort

    • array_reverse(); Reverse the original order of elements

    • ##Array pointer operation


  • reset(); Point the array pointer to the first element

    • end(); Point the array pointer to the last element

    • next(); The array pointer moves one position backward

    • prev(); The array pointer moves forward one position

    • current(); Returns the current element pointed to by the pointer

    • Other simple operations on the array


  • Array assignment to variables

    • list(

    • ##item1) = array(' ha','haha','hahaha'); Directly assign the first two elements of the array to variablesQuickly create an array

    • range( 2,10,2) Create an array from 2 to 10. Each element spans 2
    • Press the elements in the pop-up array
    • array_push($arr,'ha','haha') fills the elements into the array
    • array_pop($arr) will pop the last element of the array and the pointer jumps directly to the first element An element
    • Change the case of the array index
    • array_change_key_case($arr,CASE_UPPER/CASE);
    • Get the intersection between arrays
    • ##arr1,$arr2 value and index are both To do the sameExchange the index and element of the array

      array_filp($arr);

    • Quickly fill array elements

    • array_file(2,10,'haha') Fill a value for the index 2-10

    • Calculate the element in The number of occurrences in the array

    • array_count_values($arr) generates an array to count how many times each element in the array appears

    • Judge the number of occurrences in the array Whether the index exists

    • array_key_exists('haha',$arr)

    • Get the index in the value

    • array_key($arr)

    • Traverse each element in the array execution method

    • array_map('cube'// Method name, $arr);

    • Other functions

    • in_array('haha',$arr); Determine whether a value exists in the array Medium

    • key('haha',$arr); Get the index of the current element

    • ##String processing
    • String splitting and merging

explode(',',$str,2//Number of segments to split) Split The string is an array

  • implode(',',$arr) concatenates the array elements into a string

    • of the string Compare and Replace

    • strcmp(

    • str2) Compare Whether the two strings are the same returns a bool value

      str_replace('str'//The content to be replaced,

    • str2The string being replaced); Replace part of the content

    • str_replace('haha',

      str2) Single content replacement

    • str-replace(

      arr2,$str) Replace multiple words, replace the two arrays one by one

  • ##print($str) Output the print string

  • String formatting


    • %d Convert to decimal

    • %b Convert to binary

    • %1.2f is converted into a floating point number and retains two decimal places

    • %c is converted into the corresponding ASCLL code

    • Convert %s to string

    • ##sprintf('haha%shahahah�hahahah','haha',123)
    • Placeholder

    substr(
  • ##num1 ,$num2) Intercept a string

    Remove the whitespace characters of the string'

  • trim($str) Remove the blank characters at the beginning and end of the string
    • ltrim($str) Remove the blank characters at the beginning of the string
    • rtrim($str) Remove the characters The whitespace characters after the string
    • Convert the characters to upper and lower case

  • ##strtoupper($str) Convert to upper case
    • strtolower($str) Convert to lower case

    • ##Prevent the compilation of html tags in the string < -> &it


  • htmlentities($str)

    • ##Restore tag compilation in string &it -> <

  • html_entity_decode($str);

    • str_repeat($str,3); Repeat to generate one String

    str_pad($str,10,”*”,STR_PAD_BOTH/LEFT/RIGHT) Complete the string length by repeating a certain string
  • str_split($str,3) Split characters into arrays, no length is set, split into single characters by default
  • String hash encryption
  • md5($str1);

    • sha1($str1);
    • Operation directories and files

    • Directory operations

Open and close directories


    • path) Open the directory to obtain the handle closedir($dh) Complete the file operation and close the handle Release resources

    • #Get the file name in the next directory in the directory readdir($dh); The parameter is the handle

  • Output sequence./../The following is sorted by the first character of the file

    • Get all the files in the directory and put them into the array scandir($path) The parameter is the path
    • Modify the location of the current php file

  • getcwd() gets the path of the current php

    • chcwd($path) Modify the current php path
    • File operation

    Open and close files

  • r Read only from scratch

    • r Read and write from scratch
    • w Write only clear the file and create the file from scratch No files
    • w Read and write clear the file Create the file from scratch
    • a Write only If it starts from the tail, create
    • a. For reading and writing, if it starts from the tail, it will create
    • fopen(
    • mode); Open the file to get the handlemode and open the file in the mode

    • close($fp); Close the file handle to release resources


    • Read the file

  • feof($fp) Determine whether the end of the file is reached

    • fgets($fp,10); Read a line of the file, if there is a second parameter, get the length of the second parameter
    • Read the entire file
    • readfile($path) returns the number of bytes in the entire file
    • file($path) returns an array, each element is the content of each line

    • get_file_content returns the content of the entire file

  • Write file

    • fwrite(

      str,$length) Write file contents

    • file_put_contents(

      content) Equivalent to fopen; fwrite(); fclose(); three-in-one

  • ##Get file-related information


    • fileowner($path); Returns the file owner`

    • filesize($path) gets the file size

    • filetype($path) Get the file type

  • Function to determine the nature of the file


    • is_dir( $path) Determine whether the path is a folder

    • is_file($path) Determine whether the path is a file

    • is_readable($path) Determine the file Whether it is readable

    • is_wirtable($path) determines whether the file is writable

  • Get the file name and directory name of the path


    • basename($path) gets the file name

    • dirname($path) gets the name of the directory folder

  • file_exists($path) Determine whether the file exists

  • Create and delete the folder


    • mkdir($path); Create folder

    • rmdir($path); Delete folder

  • Create new delete assignment folder


    • ##copy(
    • path2 )Copy the file to the specified path

    • unlink($path)Delete the file
    • rename(
    • path2) Move files

    Lock of file processing (to prevent multiple users from writing at the same time)
  • flock($fp,[LOCK_EX]); The write lock can only be written by a single person
    • flock($fp,[LOCK_UN]); Release lock
    Change file attributes

  • ##chgrp(
    • group) Change the group of the file

      chmod($file,0777) Change the file mode
    • chown($path,'root'); Change the owner of the file
    • Get the file time attribute and return the timestamp

  • filetime($path) returns the last access time
    • filemtime($path) returns the last file modification time
    • filectime($path) Returns the time when the inode was last modified
    • fgetss($path); Gets the file through http protocol and gets the content to filter out html Tag
  • Introduce another php into a php file, similar to the introduction of js files

  • ##include($path) ;Introduction of files will only give a warning if the file is lost
    • require($path);Introduction of files If the file is lost, the entire program will make an error

    • # #Processing date and time
    Formatting date and time

date('Y-m-d H:i:s'); Formatting practice date

  • Format characters


  • Y year

    • mmonth

    • d Day

    • D Week

    • H Hour

    • i Minute

    • s seconds

    • ….

    • UNIX timestamp (from 1970 1 The number of seconds calculated starting at 0:00 on the 1st of the month)


  • mktime(

    • minute,

      month,

      ##year) If the parameter is omitted, the current time is

    • date ('M-d-Y',mktime(….));Convert the timestamp into days, minutes and seconds…

  • Get the information of all parts of each time and fill it into the array and Return an array


    • ##getdate([mktime(…)]) to get the current time information or timestamp time information
    • checkdate(
    • day,$year) Determine whether it is valid

For URL and HTTP processing

url address analysis

##urlencode($str) Encoding the url is to convert the non-digits and non-letters in the url Into %xx two-digit hexadecimal number
  • ##urldecode($str); Convert %xx into the original character

  • parse_url($url) returns an array containing various information of the url


  • scheme protocol
    • host host ip address And domain name

    • port port number

    • pass user name

    • pass user password

    • path access path

    • query query parameter is the information behind the url

    • fragment parameter fragment

    • Generate HTTP header

header($str) header is used to describe the server communication process and communication time must be in all actual The predefined variables obtained in front of the output

  • Get the header information


  • $_SERVER All server header information array
    • $_HTTP_HOST http host

    • $_SERVER_NAME server name

    • $_SERVER_ADDR server address

    • $_SERVER_PORT Server port

    • $_SERVER_PROTOCOL Server protocol

    • Generate using cookie

setcookie(name //cookie name,[value//cookie value, exprire//cookie expiration time, path//valid path, domain//valid domain name, secure//https secure transmission valid]) Generate cookie

  • $_COOKIE['cookiename'] Get cookie

  • setcookie('mycookie[love]','yisayu '); Generate array cookie

  • setcookie('mycookie','yisayu',time() 60*60)/mktime(0,12,12,45,2017);set Cookie validity period: The cookie will expire after 1 hour. If not set or set to 0, the cookie will expire when the browser is closed.

  • The cookie will be sent back to the page in the same directory by default. If you want to send it back to a different page, Pages in the directory


  • setcookie('mycookie','yisayu',0,'/user/'); will be sent back to all pages in the user directory Page
    • setcookie('mycookie',”) Delete cookie
  • Mathematical operation
Common Math operations

abs($num) absolute value

  • ceil($num) ceiling

  • floor($num)floor

  • sqrt($num) square root

  • round($num, 1) rounding The second parameter is reserved Rounding of decimal places

  • Decimal conversion

decbin($num) ten to two

  • dechex($num) ten to sixteen

  • decoct($num) ten to eight

  • bindec($num) two to Ten

  • octdec($num)eight to ten

  • base_convert($num,16,2) Convert num from the base of form To the base of to

  • Generate a random number

mt-rand(

  • max) Generate random numbers

    Get system information
Get the environment variables to add php

Getting php environment variables has the same effect as $_SERVER


  • ##getenv('DOCUMENT_ROOT') The environment variable is the file root directory

    • getenv('SCRIPT_NAME')Current file

    • …..

    • putenv('NAME =$env_var');

  • View loaded modules

get_load_extensions() Return array

  • get_load_extensions_funcs($moudle) Returns a specified module information

  • Gets various information of php

phpinfo(); Gets the current php Various information

  • getmypid() returns the current pid number

  • get_current_user() returns the name of the owner of the current program

Related recommendations:

A brief introduction to the basics of PHP

Basic learning about php

The above is the detailed content of Basic operations of php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!