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

$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
foreach ($arr as $key => $value) {
    if ($value % 2 == 0) {
        unset($arr['$key']);
    }
}
$numbers = [1, 2, 3, 4, 5];
echo min($numbers); // Outputs 1
echo max($numbers); // Outputs 5
$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);
foreach($users as $key => $user) {
	echo $key.': '.$user;
}
for ($i = 0; $i < count($users); $i++) {
    echo $users[$i];
}
$settings = [
    'send_from_phone' => '',
    'days_before_notify' => '0',
    'time_to_notify' => '09:00',
    'send_from_email' => ''
];

//multi-dimension array
$settings = [
    'receipents' => ['abc@gmail.com', 'xyz@gmail.com', 'another@gmail.com'],
    'working_days' => ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
];
//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);
$languages = ["Go", "Dart", "Kotlin", "Swift"];
 
$deletedlanguages  = array_pop($languages);
$japaneseNames = [
        '6' => 'Oda',
        '54' => 'Mitsuru',
        '17' => 'Kenichi',
        '1' => 'Saitama'
    ];
$japaneseNames = array_values($japaneseNames);
$movies = ["The Godfather", "A Few Good Men", "Jurassic Park"];
array_unshift($movies , 'Titanic');

Class & Object

$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);
$invoice = new stdClass();
$invoice->id = 5;
$invoice->number = "INV-2022050005";

Datetime

$last_day = date("t", strtotime("February"));
echo $last_day; //28
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';
}
$datetime = '2019-01-01 12:00:00';
$timestamp = strtotime($datetime);
echo $timestamp; //1546344000

//current timestamp
print strtotime(date('Y-m-d H:i:s'));
print date("d");
print date("m");
print date("Y");
print date("m-d-Y");
print date("Y-m-d H:i:s");
//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

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

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

//redirect user to any page
header('Location: https://example.com/form-handling/');
header('Location: ' . $_SERVER['HTTP_REFERER']);
header("Location: ".$_SERVER['REQUEST_URI']);

Network

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

Number

$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
$number = "1000.0001";
echo number_format($number, 2, '.', '');
//output: 1000.00
echo number_format($number, 2, '.', ',');
//output: 1,000.00
//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;
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

$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: 'ĂȘ'
$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>';
}
$source = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
$source = str_shuffle($source);
$length = 8;
$randomString = substr($source,  0, $length);
$fruit = 'apple,orange,banana,pear';
$fruit_array = explode(',', $fruit);


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

Text

$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

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("GREETING", "Hello world!");
echo GREETING; //"Hello world!"

define("WEB_ROOT", "https://tleapps.com/");
echo "The URL is ".WEB_ROOT;
//command line
php -v

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

Variable

//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.

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