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!

PHP Code Snippets

Array & List

Insert an Item at the Beginning of An Array —
$movies = ["The Godfather", "A Few Good Men", "Jurassic Park"];
array_unshift($movies , 'Titanic');
Remove an Array Element in a foreach Loop —
$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
foreach ($arr as $key => $value) {
    if ($value % 2 == 0) {
        unset($arr['$key']);
    }
}
Get Min or Max Value of an Array —
$numbers = [1, 2, 3, 4, 5];
echo min($numbers); // Outputs 1
echo max($numbers); // Outputs 5
Remove Duplicate Values of an Array in PHP —
$array = ["Samsung Galaxy Note 10", "Apple iPhone 13 Pro", "Samsung Galaxy Note 10", "Apple iPhone 13 Pro Max", "Apple iPhone 13 Pro"];
$result = array_unique($array);
Loop Through an Array —
foreach($users as $key => $user) {
	echo $key.': '.$user;
}
for ($i = 0; $i < count($users); $i++) {
    echo $users[$i];
}
Define an Array in PHP —
$settings = [
    'send_from_phone' => '',
    'days_before_notify' => '0',
    'time_to_notify' => '09:00',
    'send_from_email' => ''
];

//multi-dimension array
$settings = [
    'receipents' => ['[email protected]', '[email protected]', '[email protected]'],
    'working_days' => ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
];
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 —
$languages = ["Go", "Dart", "Kotlin", "Swift"];
 
$deletedlanguages  = array_pop($languages);
Array of Country Phone Codes —
//a preview, view the post for the full array
$phoneCodes=['AF'=>'93','AL'=>'355','DZ'=>'213','AS'=>'1-684','AD'=>'376','AO'=>'244','AI'=>'1-264','AQ'=>'672'];
Reset Array Keys —
$japaneseNames = [
        '6' => 'Oda',
        '54' => 'Mitsuru',
        '17' => 'Kenichi',
        '1' => 'Saitama'
    ];
$japaneseNames = array_values($japaneseNames);

Class & Object

Merge 2 Objects —
$product1 = new stdClass();
$product1->id = 1;
$product1->name = 'LED Lamp';
$product1->brand = 'Xiao Mi';

$product2 = new stdClass();
$product2->id = 2;
$product2->name = 'Large Meeting Table';

$product = (object) array_merge((array) $product1, (array) $product2);
Create a Blank Object —
$invoice = new stdClass();
$invoice->id = 5;
$invoice->number = "INV-2022050005";

Datetime

Get the Last Day of a Month —
$last_day = date("t", strtotime("February"));
echo $last_day; //28
Compare Date and Time —
if ( strtotime('2022-05-20') > strtotime(date('Y-m-d', mktime(0, 0, 0, 5, 21, 2022))) )
   // do something
}

if (new DateTime('2022-05-25') < new DateTime()){
	echo 'Expiration date';
}
Convert Datetime String to Timestamp —
$datetime = '2019-01-01 12:00:00';
$timestamp = strtotime($datetime);
echo $timestamp; //1546344000

//current timestamp
print strtotime(date('Y-m-d H:i:s'));
Get Current Date and Time —
print date("d");
print date("m");
print date("Y");
print date("m-d-Y");
print date("Y-m-d H:i:s");
Set Timezone —
//use timezone name with PHP date
date_default_timezone_set('America/Anchorage');
$datetime = new DateTime('2022-05-22T05:30:00', new DateTimeZone('America/Cordoba'))

Debug & Profiling

preg_match() vs strpos() Performances —
$time_start = microtime(true);

for ($i = 0; $i < 100000; $i++) {
    preg_match('/abc/', 'abcdefabc');
}


$time_end = microtime(true);
$time = $time_end - $time_start;
echo "preg_match(): $time <br/><br/><br/>";


$time_start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    strpos('abcdefabc', 'abc');
}

$time_end = microtime(true);
$time = $time_end - $time_start;
echo "strpos(): $time\n";
Profiling PHP Scripts without External Libraries —
$start = microtime(true);
// Enter your code here, enjoy!
$array = array("1" => "Debugging...",
    "emoji" => "😄 😁 😆", 
    "number" => rand(100,999),
    "version" => phpversion()
);

foreach( $array as $key => $value ){
    echo $key."\t=>\t".$value."\n";
}
$end = microtime(true);

echo sprintf("Elapsed:  %f", $end - $start).PHP_EOL;

echo sprintf("Used RAM:  %s bytes", memory_get_usage());

File

Force a PDF File to Be Opened in the Web Browser —
header('Content-type: application/pdf');  
header('Content-Disposition: inline; filename="myPDF.pdf"'); 
header('Content-Transfer-Encoding: binary'); 
header('Accept-Ranges: bytes'); 
@readfile('myPDF.pdf'); 

Form

Delete $_POST Variable On Page Refreshing —
//redirect user to any page
header('Location: https://example.com/form-handling/');
header('Location: ' . $_SERVER['HTTP_REFERER']);
header("Location: ".$_SERVER['REQUEST_URI']);

Network

Enable cURL —
//Add the following line to php.ini file
extension=curl

Number

Convert String to Integer and Float —
$string = '12.34 Dollars';
$int = intval($string); //12
$float = floatval($string); //12.34

$string = '$12.34 Dollars'; //not starting with a number
$int = intval($string); //0
$float = floatval($string); //0.0

$string = "150.99";
$int = (int) $string; //150
$float = (float) $string; //150.99
Format a Number in 2 Decimal Places and Grouped Thousands —
$number = "1000.0001";
echo number_format($number, 2, '.', '');
//output: 1000.00
echo number_format($number, 2, '.', ',');
//output: 1,000.00
Round a Number to the Nearest 5 or 10 —
//round to the nearest 5
$roundedNumber = (ceil($number)%10 === 0) ? ceil($number) : ceil($number/5)*5;
$roundedNumber = (floor($number)%10 === 0) ? floor($number) : floor($number/5)*5;
//round to the nearest 10
$roundedNumber = round($number, -1, PHP_ROUND_HALF_UP);
$roundedNumber = round($number, -1, PHP_ROUND_HALF_DOWN);
$roundedNumber = ceil($number / 10) * 10;
$roundedNumber = floor($number / 10) * 10;
Add Leading Zeros to a Number —
echo str_pad('27', 4, "0", STR_PAD_LEFT); //0027
echo str_pad('12', 3, "0", STR_PAD_LEFT); //012
echo str_pad('5', 2, "0", STR_PAD_LEFT); //05

String

Get the First Character of a String —
$text = 'This is my text';
echo $text[0]; //output: 'T'

//use substr
echo substr($string, 0, 1); //output: 'T'
//use mb_substr
$text = 'ê123ë';
echo mb_substr($text, 0, 1, "UTF-8"); //output: 'ê'
Loop through all characters of a string in PHP —
$string = 'PHP is a versatile scripting language that can be used for web development, system administration, and even game development.';
$chars_array = str_split($string);
foreach ($chars_array as $key => $char) {
	echo $char.'<br>';
}
Generate a Random Unique Alphanumeric String —
$source = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
$source = str_shuffle($source);
$length = 8;
$randomString = substr($source,  0, $length);
Convert a String into an Array —
$fruit = 'apple,orange,banana,pear';
$fruit_array = explode(',', $fruit);


$color = 'red|green|blue';
$color_array = split('\|', $color); 
Remove non-alphanumeric characters —
$str = 'This #string has some @non-alphanumeric characters!';
$str = preg_replace('/[^a-zA-Z0-9]/i', '', $str);
echo $str; // Thisstringhassomenonalphanumericcharacters
Remove HTML Tags from a String —
$html = 'Welcome, <b>Peter</b><br />Profile';
$output = strip_tags($html, '<br>'); // 'Welcome, Peter<br />Profile'

Text

Extract Text within Parenthesis or Brackets —
$text = 'Parenthesis can be used to add friendly comments or asides. They can also be used to (emphasize information) or to set off additional information that might otherwise be disruptive.';
preg_match('#\((.*?)\)#', $text, $matches);
print $matches[1];

$text = 'These [brackets] are used to indicate something is optional.';
preg_match('#\[(.*?)\]#', $text, $matches);
foreach ($matches as $key => $match) {
    print $match.'<br/>';
}

Timer

Run a PHP Function Every X Minutes —
function someFunction() {
  var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.querySelectorAll(".result")[0].innerText = this.responseText;
      }
    };
    xmlhttp.open("GET", "some_file.php", true);
    xmlhttp.send();
}
setInterval("someFunction", 10000);

Troubleshoot

Define and Use Constants —
define("GREETING", "Hello world!");
echo GREETING; //"Hello world!"

define("WEB_ROOT", "https://tleapps.com/");
echo "The URL is ".WEB_ROOT;
Check Your Website's PHP Version —
//command line
php -v

//PHP methods and constant
phpinfo();
echo 'My PHP version is: '.phpversion();
echo PHP_VERSION;

Variable

Define and Use Global Variables —
//user global keyword
$x = 5;

function myTest() {
    global $x;
    echo "<p>Variable x inside function is: $x</p>";
} 

//use $GLOBALS
$x = 5;
$y = 10;

function sum() {
    $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
} 

sum();

echo $y; // Outputs 15
myTest(); 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close