DEV Community

loading...
Cover image for My beloved PHP cheat sheet

My beloved PHP cheat sheet

ericchapman profile image Eric Chapman Updated on ・4 min read

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

Naming conventions

<?php

$firstName = 'Mike'  // camelCase
function updateProduct() // camelCase
class ProductItem // StudlyCaps
const ACCESS_KEY = '123abc'; // all upper case with underscore separators

Enter fullscreen mode Exit fullscreen mode

Output & Input

echo 'Hello World';

// Debug output
var_dump($names);
print_r($products);

// Input from console
$name = readline('What is your name : ');

Enter fullscreen mode Exit fullscreen mode

Variables Declaration

$name = 'Mike'; //string
$isActive = true; //boolean
$number = 25; //integer
$amount = 99.95; //float

// Type comversion
$age = (int)readline('Your age: ');
echo 'Your age is' . (string)$age;

echo gettype($age); // int

echo is_int($age) // true
echo is_float(12.5) // true
echo is_string($name) // true

Enter fullscreen mode Exit fullscreen mode

Strings

//string concat
echo 'Hello ' . $name;

//string escape characters \n new line  \t tab  \\ backslash
echo "Hello Mike\nHello David";

//string interpolation
echo "Hello $name";

//string length
echo strlen($name);

// Remove space(s) before and after
echo trim($text)

// Convert to lowercase / uppercase
echo strtolower($email);
echo strtoupper($name);

// Converts the first character to uppercase
echo ucfirst($name);  // 'Mike' 

// Replace text a by text b in $text
echo str_replace('a', 'b', $text);

// String Contains (PHP 8)
echo str_contains($name, 'ke')  # true

// Find numeric position of first occurrence 
$pos = strpos($name, 'k'); # 2

// Returns portion of string (offset / length)
echo substr($name, 0, $pos); # Mi 

Enter fullscreen mode Exit fullscreen mode

Numbers

// Check if numeric
echo is_numeric('59.99'); # true

// Round a number
echo(round(0.80));  // returns 1
echo(round(0.49));  // returns 0

// Random number
echo(rand(10, 100)); # 89
Enter fullscreen mode Exit fullscreen mode

Conditionals

// Ternary operator (true : false)
echo $isValid ? 'user valid' : 'user not valid';

//Null Coalesce Operator
echo $name ?? 'Mike';  //output 'Mike' if $name is null

//Null Coalesce Assignment
$name ??= 'Mike';

// Null Safe Operator (PHP 8) will return null if one ? is null
echo $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 boolean
false, 0, 0.0, null, unset, '0', '', []

//Conditionals
if ($condition == 10) {
    echo 'condition 10'
} elseif  ($condition == 5) {
    echo 'condition 5'
} else {
    echo 'all other conditions'
}

// One line 
if ($isActive) return true;

// Null check
if (is_null($name)) {
    do something...
}

//Comparaison operation
== // equal no type check
=== // equal with type check
!= //not equal
|| //or
&& //and
> //greater than
< //less than


// Match Expression (PHP 8)
$type = match($color) {
    'red' => 'danger',
    'yellow', 'orange' => 'warning',
    'green' => 'success',
    default => 'Unknown'
};

// Check if variable declare
isset($color['red']);  # true

Enter fullscreen mode Exit fullscreen mode

Loops and Iterations

//for loop
for ($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 ($values as $value) {
    if ($value === 'two') {
        break; // exit loop
    } elseif ($value === 'three') {
        continue; // next loop iteration
    }
}
Enter fullscreen mode Exit fullscreen mode

Arrays

//Array declaration
$names = ['Mike', 'Peter', 'Shawn', 'John'];

//add to array
$names[] = 'Micheal';

// Array merge
$array3 = array_merge($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 string
echo implode(', ', $names) //output Mike, Shawn, John, Micheal

// String to Array
echo explode(',', $text); // ['Mike', 'Shawn', 'John']

// Direct access
echo $name[1] //output Peter

//loop for each array entry
foreach($names as $name) { 
   echo 'Hello ' . $name;
}

// Number of items in a Array
echo count($names);  

//Associative array:
$person = ['age' => 45, 'genre' => 'men'];

//Add to ass. array:
$person['name'] = 'Mike';

//loop ass. array key => value: 
foreach($names as $key => $value) { 
   echo $key . ' : ' . $value
}

// Check if a specific key exist
echo array_key_exists('age', $person);

// Return keys
echo array_keys($person); // ['age', 'genre']

// Return values
echo array_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 mode Exit fullscreen mode

Functions

//function declararion
function name($firstName, $lastName = 'defaultvalue') {
    return "$firstName $lastName"
}

//function call
name('Mike', 'Taylor');

//function call with named parameters (PHP 8)
name(firstName: 'Mike', lastName: 'Taylor'); // order can change

//function variables params
function name(...$params) {
    return $params[0] .   . params[1];
}

// Closure function
Route::get('/', function () {
     return view('welcome');
});

// Arrow functions
Route::get('/', fn () => view('welcome');


// Typed parameter and typed return
function display(string $first, string $last) : string {
    return "$first $last";
}

// Typed or null
function display(?string $name) {
    ...
}

Enter fullscreen mode Exit fullscreen mode

Files

//File read
$file = fopen("test.txt", "r");

//Output lines until EOF is reached
while(! feof($file)) {
  $line = fgets($file);
  echo $line. "<br>";
}
fclose($file);

// File write
$file = fopen('export.csv', 'a');
$array = ['name' => 'Mike', 'age' => 45];

//Write key name as csv header
fputcsv($file, array_keys($array[0]));

//Write lines (format as csv)
foreach ($array as $row) {
    fputcsv($file, $row); 
}
fclose($file);
Enter fullscreen mode Exit fullscreen mode

Errors

//Throw Error
if (someCondition) {
    throw new Exception('Data format error');
}

//Catch the Error
try {
  $db->checkData($data);
} catch (Exception $e) {
    echo $e->getMessage();
}
Enter fullscreen mode Exit fullscreen mode

OOP

//class declaration
class Person 
{
}

// object instantiation
$person = new Person

//class properties and constructor
class Person 
{
   protected $firstName;
   protected $lastName;
   public function __construct($firstName, $lastName) {
        $this->firstName = $firstName;
        $this->lastName = $lastName
   }

// Constructor Property Promotion (PHP 8)
class Person 
{
    public function __construct(protected $firstName, protected $lastName) 
    {

    }

//static constructor
public static function create(...$params) {
    return new self($params)
}
$person = Person::create(Mike, Taylor);

// Static Method
class greeting {
  public static function welcome() {
    echo "Hello World!";
  }
}

// Call static method
greeting::welcome();

// Static method call
class greeting {
  public static function welcome() {
    echo "Hello World!";
  }

  public function __construct() {
    static::welcome();
  }
}
new greeting();

// Static constant
class Connection
{
  const MAX_USER = 100;
}
echo Connection::MAX_USER # 100

// class inheritance
class Customer extends Person
{
    public function name()
    {
        parent::name();
        echo 'Override method';  
    }
}

// self keyword reference current class (not modify by inheritance late binding like static will be)
self::welcome();

// Interface
interface Animal {
  public function makeSound();
}

class Cat implements Animal {
  public function makeSound() {
    echo "Meow";
  }
}
$animal = new Cat();
$animal->makeSound();

//Trait (mix-in)
trait HelloWorld {
    public function sayHello() {
        echo 'Hello World!';
    }
}

class Greetings {
    use HelloWorld;
}
$object = new Greetings();
$object->sayHello();
Enter fullscreen mode Exit fullscreen mode

Discussion (13)

pic
Editor guide
Collapse
tonyketcham profile image
Tony Ketcham

More of a style thing, but for booleans I try to give them a verb name like:

  • isActive
  • isDefined
  • hasName
  • hasColor

which I’ve found makes my code read more semantically when the variables are used in conditional statements and loops

Collapse
turkindm profile image
Dmitry Turkin

Oh come on, where is PHP8 features?

Collapse
rickavmaniac profile image
rickavmaniac Author

Good point. Will add those later today.

Collapse
jonrandy profile image
Jon Randy
<?php

//Naming convention
$first_name = 'Mike'. // all lower case with underscore separators
function updateProduct() // camelCase
class ProductItem // StudlyCaps
const ACCESS_KEY = '123abc'; // all upper case with underscore separators

//output
echo 'Hello World';

//variable declaration
$name = 'Mike'; //string
$isActive = true; //boolean
$number = 25; //integer
$amount = 99.95; //float
...
Enter fullscreen mode Exit fullscreen mode

You seem to introduce a naming convention of camel case for var names, then immediately contradict it with $isActive?

Collapse
rickavmaniac profile image
rickavmaniac Author

Good point :-)

Collapse
ellisgl profile image
Ellis

I need to benchmark it again, but ++$i is a micro optimizion you can use on your for loops. IIRC, do..while is another micro optimization you replace your while loops with, if you can guarantee at least one iteration.

Collapse
bawa_geek profile image
Lakhveer Bawa

Pretty good work, I am not sure, if it's only me, I must have used "while and do-while loop" no more than 2-3 times in the last 4 years

Collapse
drbyte profile image
Chris Brown • Edited

Nice list. Note: In at least 2 cases you use __construc where it should be __construct

Collapse
rickavmaniac profile image
rickavmaniac Author

Good catch. Corrected.

Collapse
bobbyiliev profile image
Bobby Iliev

That is great! I recently wrote a similar PHP guide here.

Collapse
kosoko_daniel profile image
Daniel

Wow this is great. Weldone

Collapse
pomelchenko profile image
Info Comment marked as low quality/non-constructive by the community. View code of conduct
Pavel Omelchenko
//string number of characters
echo strlen($name);
Enter fullscreen mode Exit fullscreen mode

Length in bytes not in characters

//function declararion
function name($firstName, $lastName = 'defaultvalue') {
Enter fullscreen mode Exit fullscreen mode

Use types of attr like

function name(string $firstName, string $lastName = 'defaultvalue'): string {
    retunr "$firstName $lastName";
}
Enter fullscreen mode Exit fullscreen mode

errors

try {
    $null = null;
    retun $null ?? throw new \Exception('Yes! You can do it');
} catch (\Exception) { // yep in 8 you can use only type of exception
// ...
} final {
// sometimes can help
}
Enter fullscreen mode Exit fullscreen mode
    // ...
        self::welcome();
    // ...
Enter fullscreen mode Exit fullscreen mode

you must understand the difference between self and static