PHP Code Snippets

Every developer has their own set of go-to code snippets that they use time and time again. Here, we’ve compiled a list of some of the best PHP code snippets out there – from sorting arrays to generating unique IDs. So whether you’re just getting started with PHP or you’re looking for a new trick to add to your tool belt, this curated list is sure to come in handy!

Array & List

Convert an Array to an Object
//casting
$array = array('id' => 1, 'name' => 'PHP Example');
$article = (object) $array;

//create blank object and add array values to its fields
$array = ['id' => 2, 'name' => 'Kotlin Example'];
$article2 = new stdClass();
foreach ($array as $key => $value)
{
    $article2->$key = $value;
}

//use json_decode
$array = ['id' => 3, 'name' => 'Flutter Example'];
$article3 = json_decode(json_encode($array), FALSE);
Remove the Last Element from an Array
Reset Array Keys
Insert an Item at the Beginning of An Array

Class & Object

Create a Blank Object

Datetime

Get the Last Day of a Month
Compare Date and Time
Convert Datetime String to Timestamp
Get Current Date and Time
Set Timezone

Debug & Profiling

preg_match() vs strpos() Performances
Profiling PHP Scripts without External Libraries

File

Force a PDF File to Be Opened in the Web Browser

Form

Delete $_POST Variable On Page Refreshing

Network

Enable cURL

Number

Add Leading Zeros to a Number

String

Remove HTML Tags from a String

Text

Extract Text within Parenthesis or Brackets

Timer

Run a PHP Function Every X Minutes

Troubleshoot

Define and Use Constants
Define and Use Global Variables
Check Your Website's PHP Version

Leave a Comment

Your email address will not be published.