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
$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


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


Force a PDF File to Be Opened in the Web Browser


Delete $_POST Variable On Page Refreshing


Enable cURL


Add Leading Zeros to a Number


Remove HTML Tags from a String


Extract Text within Parenthesis or Brackets


Run a PHP Function Every X Minutes


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.