Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for PHP cheat sheet (updated to PHP 8.1)
Eric The Coder
Eric The Coder

Posted on • Edited on

     

PHP cheat sheet (updated to PHP 8.1)

Follow me!:Follow @EricTheCoder_



Here is my cheat sheet I created along my learning journey. If you have any recommendations (addition/subtraction) let me know.


PHP local server
php -S localhost:3000
Enter fullscreen modeExit fullscreen mode

Comments

// one line comment/*This is a multiple-lines comment blockthat spans over multiplelines*/
Enter fullscreen modeExit fullscreen mode

Naming conventions

// PHP opening/closing tag<?php  echo "Hello World";?>// if no closing tag the rest of the file will be considered PHP// Short syntax for PHP echo<?="Hello World"?>//Enable strict typing (first line of your PHP file)<?declare(strict_types=1);// Include a PHP filerequire'app/Product.php'// Create a namespacenamespaceApp;// Use a namespaceuseApp\Product;$firstName='Mike'// camelCasefunctionupdateProduct()// camelCaseclassProductItem// StudlyCapsconstACCESS_KEY='123abc';// all upper case with underscore separators
Enter fullscreen modeExit fullscreen mode

Output & Input

echo'Hello World';// Debug outputvar_dump($names);print_r($products);// Input from console$name=readline('What is your name : ');
Enter fullscreen modeExit fullscreen mode

Variables Declaration

$name='Mike';//string$isActive=true;//boolean$number=25;//integer$amount=99.95;//float$fruits=['orange','apple','banana']//arrayconstMAX_USERS=50;//constantdefine('MAX_USERS',50);//constant// Assign 'by reference' with the & keyword$name_2=&$name_1// Type conversion$age=(int)readline('Your age: ');echo 'Your age is'.(string)$age;echogettype($age);// intechois_int($age)// trueechois_float(12.5)// trueechois_string($name)// true
Enter fullscreen modeExit fullscreen mode

Strings

// String can use single quote$name='Mike'// or double quote$name="Mike"// Double quote string can escape characters \n = new line  \t = tab  \\ = backslashecho"Hello Mike\nHello David";// Double quote string can do interpolationecho"Hello$name";// string concatecho'Hello '.$name;// string lengthechostrlen($name);// Remove space(s) before and afterechotrim($text)// Convert to lowercase / uppercaseechostrtolower($email);echostrtoupper($name);// Converts the first character to uppercaseechoucfirst($name);// 'Mike'// Replace text a by text b in $textechostr_replace('a','b',$text);// String Contains (PHP 8)echostr_contains($name,'ke')# true// Find numeric position of first occurrence$pos=strpos($name,'k');# 2// Returns portion of string (offset / length)echosubstr($name,0,$pos);# Mi
Enter fullscreen modeExit fullscreen mode

Numbers

// Shortcut addition assignment$value=10$value++// 11// or$value+=1// 11// Shortcut subtraction assignment$value=10$value--// 9// or$value-=1// 9// Check if numericechois_numeric('59.99');# true// Round a numberechoround(0.80);// returns 1// Round a number with precisionechoround(1.49356,2));// returns 1.49// Random numberecho(rand(10,100));# 89
Enter fullscreen modeExit fullscreen mode

Conditionals

// If / elseif / elseif($condition==10){echo'condition 10'}elseif($condition==5){echo'condition 5'}else{echo'all other conditions'}// And condition = &&if($condition===10&&$condition2===5){echo'10 and 5'}// Or condition = ||if($condition===10||$condition2===5){echo'10 or 5'}// One lineif($isActive)returntrue;// Null checkif(is_null($name)){dosomething...}//Comparaison operation==// equal no type check===// equal with type check!=//not equal||//or&&//and>//greater than<//less than// Ternary operator (true : false)echo$isValid?'user valid':'user not valid';//Null Coalesce Operatorecho$name??'Mike';//output 'Mike' if $name is null//Null Coalesce Assignment$name??='Mike';// Null Safe Operator (PHP 8) will return null if one ? is nullecho$user?->profile?->activate();// Null Safe + Null Coalesce (if null will return 'No user profile')echo$user?->profile?->activate()??'Not applicable';//Spaceship operator return -1 0 1$names=['Mike','Paul','John']usort($names,function($a,$b){return$a<=>$b;}// ['John', 'Mike', 'Paul']// Return false when convert as booleanfalse,0,0.0,null,unset,'0','',[]// Compare same variable with multiple valuesswitch($color){case'red':echo'The color is red';break;case'yellow':echo'The color is yellow';break;case'blue':echo'The color is blue';break;default:echo'The color is unknown';}// Match Expression (PHP 8)$type=match($color){'red'=>'danger','yellow','orange'=>'warning','green'=>'success',default=>'Unknown'};// Check if variable declareisset($color['red']);# true
Enter fullscreen modeExit fullscreen mode

Loops and Iterations

//for loopfor($i=0;$i<20;$i++){echo"i value = ".i;}//while loop$number=1;while($number<10){echo'value : '.$number;$number+=1;}//do while$number=1;do{echo'value : '.$number;$number+=1;}while($number<10);// foreach with break / continue exemple$values=['one','two','three'];foreach($valuesas$value){if($value==='two'){break;// exit loop}elseif($value==='three'){continue;// next loop iteration}}
Enter fullscreen modeExit fullscreen mode

Arrays

//Array declaration can contain any types$example=['Mike',50.2,true,['10','20']];//Array declaration$names=['Mike','Peter','Shawn','John'];// Direct access to a specific element$name[1]//output Peter// How to access an array in an array$example[3][1]// 20//add a element to an array$names[]='Micheal';// Array merge$array3=array_merge($array1,$array2);// Merge with spreading operator (also work with associative array)$array3=[...$array1,...$array2];// Array Concat with Spread Operator$names=['Mike','Peter','Paul'];$people=['John',...$names];// ['John', 'Mike', 'Peter', 'Paul']//Remove array entry:unset($names['Peter']);//Array to stringechoimplode(', ',$names)//output Mike, Shawn, John, Micheal// String to Arrayechoexplode(',',$text);// ['Mike', 'Shawn', 'John']//loop for each array entryforeach($namesas$name){echo'Hello '.$name;}// Number of items in a Arrayechocount($names);//Associative array declaration (key => value):$person=['age'=>45,'genre'=>'men'];//Add to ass. array:$person['name']='Mike';//loop ass. array key => value:foreach($namesas$key=>$value){echo$key.' : '.$value}// Check if a specific key existechoarray_key_exists('age',$person);// Return keysechoarray_keys($person);// ['age', 'genre']// Return valuesechoarray_values($person)// [45, 'men']//Array filter (return a filtered array)$filteredPeople=array_filter($people,function($person){return$names->active;})// Array map (return transform array):$onlyNames=array_map(function($person){return['name'=>$person->name];},$people)# Search associative array$items=[['id'=>'100','name'=>'product 1'],['id'=>'200','name'=>'product 2'],['id'=>'300','name'=>'product 3'],['id'=>'400','name'=>'product 4'],];# search all value in the 'name' column$found_key=array_search('product 3',array_column($items,'name'));# return 2
Enter fullscreen modeExit fullscreen mode

Functions

//function declararionfunctionname($firstName,$lastName='defaultvalue'){return"$firstName$lastName"}//function callname('Mike','Taylor');//function call with named parameters (PHP 8)name(firstName:'Mike',lastName:'Taylor');// order can change//function variables paramsfunctionname(...$params){return$params[0]..params[1];}// Closure functionRoute::get('/',function(){returnview('welcome');});// Arrow functionsRoute::get('/',fn()=>view('welcome');// Typed parameter and typed returnfunctiondisplay(string$first,string$last):string{return"$first$last";}// Typed or nullfunctiondisplay(?string$name){...}// Union type (or)functiondisplay(string|int$data){...}// Intersection type (and)functioncount_and_interate(Iterator&Countable$value){...}// Return any type (mixed)functionlogInfo(string$info):mixed{...}// No return (void)functionlogInfo(string$info):void{...}
Enter fullscreen modeExit fullscreen mode

Enumerations

// DeclarationenumInvoiceStatus{caseSent;casePaid;caseCancelled;}// The enum can then be use as a typefunctionprintInvoiceStatus(InvoiceStatus$status){print($status->name);}printInvoiceStatus(InvoiceStatus::Sent);// Sent// enum with return value and public function exempleenumInvoiceStatus:int{caseSent=0;casePaid=1;caseCancelled=2;publicfunctiontext():string{returnmatch($this){self::Sent=>'Sent',self::Paid=>'Paid',self::Cancelled=>'Cancelled'};}}functiongetInvoiceStatus(InvoiceStatus$status){print($status->text());print($status->value);}getInvoiceStatus(InvoiceStatus::Paid);// Paid1
Enter fullscreen modeExit fullscreen mode

Files

// Get the current dir$current_dir=__DIR__;// Check if file existif(file_exists('/posts/first.txt')){dosomestuff}// Read file content into one variable$post=file_get_contents($file);//File read$file=fopen("test.txt","r");//Output lines until EOF is reachedwhile(!feof($file)){$line=fgets($file);echo$line."<br>";}fclose($file);// File write (csv)$file=fopen('export.csv','a');$array=['name'=>'Mike','age'=>45];//Write key name as csv headerfputcsv($file,array_keys($array[0]));//Write lines (format as csv)foreach($arrayas$row){fputcsv($file,$row);}fclose($file);
Enter fullscreen modeExit fullscreen mode

Errors

//Throw Errorif(someCondition){thrownewException('Data format error');}//Catch the Errortry{$db->checkData($data);}catch(Exception$e){echo$e->getMessage();}
Enter fullscreen modeExit fullscreen mode

OOP

//class declarationclassPerson{}// object instantiation$person=newPerson//class properties and constructorclassPerson{protected$firstName;protected$lastName;publicfunction__construct($firstName,$lastName){$this->firstName=$firstName;$this->lastName=$lastName}// Constructor Property Promotion (PHP 8)classPerson{publicfunction__construct(protected$firstName,protected$lastName){}// Getter and SetterclassPerson{private$name;publicfunctionsetName($name){if(!is_string($name)){thrownewException('$name must be a string!');}$this->name=$name;}publicfunctiongetName(){return$this->name;}}// Readonly properties (PHP 8.1)classPerson{publicfunction__construct(publicreadonlystring$firstName,publicreadonlystring$lastName){}}//static constructorpublicstaticfunctioncreate(...$params){returnnewself($params)}$person=Person::create(Mike,Taylor);// Static Methodclassgreeting{publicstaticfunctionwelcome(){echo"Hello World!";}}// Call static methodgreeting::welcome();// Static method callclassgreeting{publicstaticfunctionwelcome(){echo"Hello World!";}publicfunction__construct(){static::welcome();}}newgreeting();// Static constantclassConnection{constMAX_USER=100;}echoConnection::MAX_USER# 100// class inheritanceclassCustomerextendsPerson{publicfunctionname(){parent::name();echo'Override method';}}// self keyword reference current class (not modify by inheritance late binding like static will be)self::welcome();// InterfaceinterfaceAnimal{publicfunctionmakeSound();}classCatimplementsAnimal{publicfunctionmakeSound(){echo"Meow";}}$animal=newCat();$animal->makeSound();//Trait (mix-in)traitHelloWorld{publicfunctionsayHello(){echo'Hello World!';}}classGreetings{useHelloWorld;}$object=newGreetings();$object->sayHello();
Enter fullscreen modeExit fullscreen mode

Follow me!:Follow @EricTheCoder_


Top comments(15)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
anwar_nairi profile image
Anwar
Fullstack developer @ Partoo
  • Joined

Nice one Eric! You can also add this trick to make numbers even more readable

$bankBalance=1_000_000;
Enter fullscreen modeExit fullscreen mode
CollapseExpand
 
gregorgonzalez profile image
Gregor Gonzalez
  • Joined

Oh didn't know about that. Thanks 👍

CollapseExpand
 
vinceamstoutz profile image
Vincent Amstoutz
Never stops learning for new experiences! Contributes more and more to opensource projects.
  • Location
    Lyon, France
  • Education
    Master of project management and programming (web & software)
  • Work
    Senior dev at Les-Tilleuls.coop
  • Joined

Oh like in the JS env ! Thanks for this trick@khalyomede ! 😊

CollapseExpand
 
vladi160 profile image
vladi160
A dev since IE6
  • Location
    Sofia, Bulgaria
  • Joined

Invokable classes:

class A {
public function __invoke() {
print_r('Hello world!);
}
}
$a = new A();
($a)(); // 'Hello World'

array_reduce:

$total = array_reduce(
$arr,
function($ac, $item) { return $ac + $item; },
0
);

Destructuring arrays:

$arr = [
[1, 'name1'],
[2, 'name2'],
];

[$firstEl, $secondEl] = $arr ; // firstEl = [1, 'name1'], secondEl = [2, 'name2']
[$id, $name] = $firstEl; // $id = 1 | $name = name1

Destructuring in a loop:

`foreach ($arr as [$id, $name]) {

}`

CollapseExpand
 
mlsofts profile image
MLSofts
  • Joined

Thank you for the very interesting article, however I have two comments while going through the article:

the first in Conditionals: switch ($ color) there are two "red" cases
the second in array: // Array declaration can contain any types
$ example = ['Mike', 50.2, true, ['10', '20'];
a "]" is missing at the end

CollapseExpand
 
ericchapman profile image
Eric The Coder
Businessman and blogger #Javascript, #Python and #PHP. My favorite frameworks/librairies are #React, #Laravel, and #Django. I am also a fan of #TailwindCSS
  • Location
    Canada
  • Joined

Done. Thanks

CollapseExpand
 
nicholas_moen profile image
arcanemachine
  • Joined
• Edited on• Edited

Nice cheatsheet. Very helpful.

FYI, classes don't usesTuDLy cApS, they usePascalCase aka UpperCamelCase (becausecamel case can mean either camelCase or CamelCase, making the word completely useless... the term lowerCamelCase should be used to avoid confusion).

CollapseExpand
 
gregorgonzalez profile image
Gregor Gonzalez
  • Joined

Love to see all php8 stuff 🤩

CollapseExpand
 
bigdan256 profile image
BigDan256
  • Location
    Australia
  • Work
    Programming Generalist
  • Joined

Great cheat sheet.

Try to use <?php in place of <? as the tag isn't enabled in recommended production or development environments:
; short_open_tag
; Default Value: On
; Development Value: Off
; Production Value: Off
When you use it and it's not enabled, either your file will error out, or your source code will leak to your output.

Try var_export, it's similar to var_dump and print_r. It outputs content in php syntax, similar to how json_encode will return content in json syntax.

CollapseExpand
 
salehmubashar profile image
Saleh Mubashar
Frontend Developer and Technical Writer
  • Joined

wow, i must say this is quite comprehensive.
I think you could addSuperglobals as well
thanks :)

CollapseExpand
 
llbbl profile image
Logan Lindquist
I dream of a world that is fair and equitable in its society and has a sustainable impact to our environment.
  • Location
    Austin, TX
  • Work
    Engineerer at Legacy Beta Inc
  • Joined

nice job Eric

CollapseExpand
 
ridwanishaq profile image
ridwanishaq
  • Joined

Very helfull, thank very much for this wonderful articles

CollapseExpand
 
code_jedi profile image
Code_Jedi
Javascript, Node.js, Python, PHP, React and Vue.Coding since 2017
  • Joined

Thank you! As a PHP developer, I see myself coming back to this over the next couple of months.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Businessman and blogger #Javascript, #Python and #PHP. My favorite frameworks/librairies are #React, #Laravel, and #Django. I am also a fan of #TailwindCSS
  • Location
    Canada
  • Joined

More fromEric The Coder

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp