Demos
Get parameter from a post call, input name inputname | $_POST['inputname'] |
Get parameter from a get call, input name inputname | $_GET['inputname'] |
Get the server accessed (for example localhost) | $_SERVER['SERVER_NAME'] |
Get the part of the url after the server name | $_SERVER['REQUEST_URI'] |
Get the port | $_SERVER['SERVER_PORT'] |
Get information if https is used | $_SERVER['HTTPS']; |
Logical operator not | ! |
Logical operator and | && |
Logical operator or | || |
Get result from listing of a folder in a parameter | $myparameter=`ls -la` |
check if a parameter is a string | is_string($myparameter) |
check if a parameter is null | is_null($myparameter) |
check if a parameter is numeric | is_numeric($myparameter) |
check if a parameter is set | isset($myparameter) |
check if a parameter is not set or empty | empty($myparameter) |
Convert to integer | $result=intval($inputparameter); |
Convert to string | $result=strval($inputparameter); |
If else | if (condition) { ... } else { } |
Switch | switch($inputparameter){ case "a" : ... break; case "b" : ... break; default : ... break; } |
while | while ( conditiontocontinue ){ ... } |
for loop | for ( $i=0 ;$i <=$imax ;$i++) { } |
get out of a loop | exit |
open a text file to add content at the end | $filepointer=fopen("filepath","at"); |
when opening, symbol to modify from the beginning | w |
when opening, symbol delete file if existing, otherwise write from the beginning | w+ |
when opening, symbol add content at the end, create file if not existing | a+ |
Write in a file | int fwrite($filepointer,$inputstring,strlen($inputstring)); you get $filepointer from fopen |
Close a file | close($filepointer); |
Prevent file locking | flock($filepointer,LOCK_NB); |
Lock file for writing | flock($filepointer,LOCK_EX); |
Lock file for reading | flock($filepointer,LOCK_SH); |
Unlock file | flock($filepointer,LOCK_UN); |
Read file line by line (but don't read more than 999 bytes) | while (!feof($filepointer)) { $line=fgets($filepointer,999); |
Read a line but take off all php and html characters | fgetss($filepointer,999,$allowedspecialcharacters); |
Read a line from a csv file with tab separator | fgetcsv($filepointer,100,"\t"); |
Test if file exists | file_exists($filepath) |
Get the file size | filesize($filepath) |
Delete a file | unlink($filepath) |
Initialize an array | $myarray=array(value1,...); |
Initialize an empty array | $myarray=array(); |
Make an array containing numbers from 1 to 10 | $mylist=range(1,10); |
Access first element of the array and put in a variable | $myelement=$myarray[0]; |
Show the content of the array | print_r($myarray); |
Use each element of the array | foreach ( $myarray as $variable ) { echo $variable; } |
Initialize an array with keys | $myarray=array(key1=>value1,key2=>value2,...); |
Use each element of the array, get keys and values | foreach ( $myarray as $key=> $value ) { echo $key." : ".$value; } |
Initialize an array of arrays | $myarray=array ( array (a11,a12), array (a21,a22) ); |
Sort an array | sort($myarray); |
Array with keys and values: sort per keys | ksort($myarray); |
Array with keys and values: sort per values | asort($myarray); |
Inverted sort | Add an r before sort: rsort, krsort, arsort |
Custom sort=indicate how I know an element is before another | function mycomparison($x,$y) { .... algorithm returning 0, 1 or -1 } usort($myarray,'mycomparison'); |
Put a random order in elements of the array | shuffle($myarray); |
Add an element at the end of an array | array_push($myarray,$myelement); |
Take of the last element of an array | array_pop($myarray); |
Get the last element of an array and stay on this position | $myvalue=end($myarray); |
Get the next element in an array and stay on this position | $myvalue=next($myarray); |
Get the previous element in an array and stay on this position | $myvalue=prev($myarray); |
Get the first element of an array and stay on this position | $myvalue=reset($myarray); |
Modify each element of an array using a function multiplying by 3 each element in the array | function mymodificator(&$inputvalue,$mykey,$myvalue) { $inputvalue*=$myvalue; } array_walk($myarray,'my_modification',3); |
Number of elements in an array | count($myarray) or sizeof($myarray) |
Get the list of values with the number of occurence per value | array_count_values($myarray); |
Take off spaces from a string | $result=trim($input); |
Convert all returns to | $result=nl2br($input); |
Print something in a certain format using a parameter | printf("This is a text : %s",$value); |
format: float with 2 digits after decimal point | %.2f |
format: string of 4 characters, fill-in with x on right if less than 4 characters | %'0-4s |
format: string of 5 characters | %5s |
format: integer of 9 digits, fill-in with zeroes on the left | %'.09d |
format: take second parameter as an integer of 4 digits filled-in with 0 if less | %1\$s |
Change to upper case | strtoupper($input) |
Change to lower case | strtolower($input) |
Change first letter to upper case | ucfirst($input) |
Change first letter of each word to upper case | ucwords($input) |
Trim and escape special characters | addslashes(trim($input)) |
Convert string to array, using ;as delimiter | explode(';',$input) |
Convert back array to string (delimiter ;) | implode(';',$myarray) |
Take part of a string | substr($inputstring,start,[lenght]) |
From bibula, take bul | substr("bibula",2,3) |
From bibula, take ibula | substr("bibula",1) |
Compare two strings | strcmp($firstinput,$secondinput) 0 if same >0 if $firststring>$secondstring (or if first string is higher in alphabet than second string) |
Number returned when comparing a,b | -1 |
Compare, NOT taking into account upper or lower case | strcasecmp() |
Get the length of a string | strlen($inputstring) |
Look for string in string | $test=strpos($inputstring,$searchedstring); returns null if not found |
Look for string in string, starting from position n | $test=strpos($inputstring,$searchedstring,n); |
Look for string in string, give last position | $test=strrpos($inputstring,$searchedstring); |
Replace string1 by string2 inside string | str_replace($string1,$string2,$string) |
Regular expression: 1 or more (not 0) | + |
Regular expression : 0, 1 or more | * |
Regular expression: dot | \. |
Regular expression: any lower case letter or dash | [a-z\-] |
Regular expression: tabulators and spaces | [[:space]] |
Regular expression: word | \w |
Regular expression: number | \d |
Regular expression: aa or ab or ac | aa|ab|ac |
Regular expression: \ | \\ |
Give array of strings matching the expression | $result=preg_match($expression,$inputstring,$arrayoffound); |
Case insensitive search | /i |
Declare regular expression | $expression='/regularexpression/' |
Replacement pattern: second group | ${2} |
Replacement pattern: form a group | (group) |
Make replacements | $result=preg_replace($expression,$replacementpattern,$inputstring); |
Separate string in array elements using regular expression example: separator is @ or . | $array=split("\.|@",$inputstring); |
get code from mycode.php without critical | include('mycode.php'); |
get code from mycode.php making sure it is done only once | include_once('mycode.php'); |
Function: get number of arguments | $number=func_num_args(); |
Function : loop through all arguments | $arguments=func_get_args(); foreach ( $arguments as $argument) {... |
Function returning a result | function myFunction(){ return $myresult; } $result=myFunction(); |
Class with constructor | class myClass { private $objectparam; function __construct($myparam) { $this->$objectparam=$myparam; } } |
Class with getter and setter | class myClass { private $objectparam; function __construct($myparam) { $this->$objectparam=$myparam; } function __get($myparam) { return $this->$myparam; } function __set($myparam,$myvalue) { $this->$objectparam=$myvalue*2; } function printvalue() { echo "value of object param:".$this->$objectparam; } } |
Get instance of class | $myobject=new className(); |
Call function | $myobject->functionName(); |
Get value of parameter (calling getter) | $result=$classpointer->$parametername; |
Set value of parameter ( calling setter) | $classpointer->$parametername=$value; |
Class B is child of A | class B extends A |
Interface definition | interface myInterface { function myFunction(); } |
Class implementing the function in interface | class myClass implements myInterface { function myFunction() { ... } } |
Catch error | try { ... } catch (Throwable $t) { ..... } |
Get all details about the error | getMessage — Gets the message getCode — Gets the exception code getFile — Gets the file in which the object was created getLine — Gets the line on which the object was instantiated getTrace — Gets the stack trace getTraceAsString — Gets the stack trace as a string getPrevious — Returns the previous Throwable __toString — Gets a string representation of the thrown object |
Connect to an sql database (object oriented) | $connectionobject=new mysqli($myhost, $myuser, $mypassword, $mydatabase); ... $connectionobject->close(); |
Connection error | $connectionobject->connect_errno |
Execute a query | $resultpointer=$mysqli->query("SELECT * from TEST")); .... $resultpointer->free(); |
Get number of rows | $resultpointer->num_rows |
Get each row in a table in which column names are keys | for ($i=0;$i<$numberofrows;$i++) { $currentline=$resultpointer->fetch_assoc(); } |
Get an element of the row | $currentline['columnname']; |
Get each row in a table (without keys) | fetch_row() |
Query with mask | $myquery="insert into mytable values (?,?)"; $myinstruction=$connectionpointer->prepare($myquery); $myinstruction->bind_param($param1,$param2); $myinstruction->execute(); ... $myinstruction->affected_rows ... $myinstruction.close(); |