So here’s a new list of useful PHP functions and code snippets to help you in your projects.
First up, let’s see a neat way to output an SVG element:
// Load an inline SVG.
function load_inline_svg( $filename ) {
// Check the SVG file exists
if ( file_exists( $filename ) ) {
// Load and return the contents of the file
return file_get_contents( $filename );
}
// Return a blank string if we can't find the file.
return '';
}
and how I typically use it in say a Wordpress project:
echo load_inline_svg(get_template_directory() . '/img/icons/icon__leaf--green.svg');
Next, ever needed to create a slug from a string? This will convert a string from Hello World
to hello-world
.
function slugify($string) {
return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $string), '-'));
}
This one is Wordpress and Advanced Custom Fields specific, but it simply uses Wordpress to make a database request to get a field by its meta key.
function get_acf_key($field_name) {
global $wpdb;
$length = strlen($field_name);
$sql = "
SELECT `meta_key`
FROM {$wpdb->postmeta}
WHERE `meta_key` LIKE 'field_%' AND `meta_value` LIKE '%\"name\";s:$length:\"$field_name\";%';
";
return $wpdb->get_var($sql);
}
These next two functions just take a string and convert it to a base64 url and vice versa.
// Encode String to Base64
function base64url_encode($plainText) {
$base64 = base64_encode($plainText);
$base64url = strtr($base64, '+/=', '-_,');
return $base64url;
}
// Decode String to Base64
function base64url_decode($plainText) {
$base64url = strtr($plainText, '-_,', '+/=');
$base64 = base64_decode($base64url);
return $base64;
}
This function is useful for determining the client’s language.
function get_client_language($availableLanguages, $default='en'){
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
foreach ($langs as $value){
$choice=substr($value,0,2);
if (in_array($choice, $availableLanguages)){
return $choice;
}
}
}
return $default;
}
Ever need to append th, st, nd, rd to a number? Pass the value to this function and it’ll return the number’s ordinal.
// Add (th, st, nd, rd) to the end of a number
function ordinal($cdnl){
$test_c = abs($cdnl) % 10;
$ext = ((abs($cdnl) % 100 < 21 && abs($cdnl) %100 > 4) ? 'th'
: (($test_c < 4) ? ($test_c < 3) ? ($test_c < 2) ? ($test_c < 1)
? 'th' : 'st' : 'nd' : 'rd' : 'th'));
return $cdnl . $ext;
}
For the lazy programmer, this function simply checks if a string begins with substring.
function startsWith($string, $startString) {
$len = strlen($startString);
return (substr($string, 0, $len) === $startString);
}
Extract emails from a string:
function extract_emails_from($string) {
preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $string, $matches);
return $matches[0];
}
Make sure an email is 👌 using regex:
function check_email($email) {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/",$email)) {
list($username,$domain)=split('@',$email);
if (!checkdnsrr($domain,'MX')) {
return false;
}
return true;
}
return false;
}
Title kinda says it all, a useful function for sorting lists of data:
function order_by($items, $attr, $order) {
$sortedItems = [];
foreach ($items as $item) {
$key = is_object($item) ? $item->{$attr} : $item[$attr];
$sortedItems[$key] = $item;
}
if ($order === 'desc') {
krsort($sortedItems);
} else {
ksort($sortedItems);
}
return array_values($sortedItems);
}
Gets the median of numbers. Numbers are passed as an array.
function median($numbers) {
sort($numbers);
$totalNumbers = count($numbers);
$mid = floor($totalNumbers / 2);
return ($totalNumbers % 2) === 0 ? ($numbers[$mid - 1] + $numbers[$mid]) / 2 : $numbers[$mid];
}
Gets the average of numbers. Numbers are passed as an array.
function calculate_average($numbers) {
$count = count($numbers);
foreach ($numbers as $value) {
$total = $total + $value;
}
$average = ($total / $count);
return $average;
}
Check if an array has duplicates:
function has_duplicates($items) {
return count($items) > count(array_unique($items));
}
Convert an RGB color code to hex color code.
function rgb2hex($r, $g = null, $b = null) {
if (strpos($r, 'rgb') !== false || strpos($r, 'rgba') !== false) {
if (preg_match_all('/\(([^\)]*)\)/', $r, $matches) && isset($matches[1][0])) {
list($r, $g, $b) = explode(',', $matches[1][0]);
} else {
return false;
}
}
$result = '';
foreach ([$r, $g, $b] as $c) {
$hex = base_convert($c, 10, 16);
$result .= ($c < 16) ? ('0'.$hex) : $hex;
}
return '#'.$result;
}
ie:
rgb2hex("rgb(0,0,0)")
Get the favicon of a site using Google’s internally stored ones:
function get_favicon($url) {
return 'https://www.google.com/s2/favicons?domain=' . urlencode($url);
}
This function is a straightforward PHP check to see if you’re actually serving HTTPS.
function is_https() {
return isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
}
Convert a number to a string (word):
function number_to_word($number) {
$hyphen = '-';
$conjunction = ' and ';
$separator = ', ';
$negative = 'negative ';
$decimal = ' point ';
$fraction = null;
$dictionary = [
0 => 'zero',
1 => 'one',
2 => 'two',
3 => 'three',
4 => 'four',
5 => 'five',
6 => 'six',
7 => 'seven',
8 => 'eight',
9 => 'nine',
10 => 'ten',
11 => 'eleven',
12 => 'twelve',
13 => 'thirteen',
14 => 'fourteen',
15 => 'fifteen',
16 => 'sixteen',
17 => 'seventeen',
18 => 'eighteen',
19 => 'nineteen',
20 => 'twenty',
30 => 'thirty',
40 => 'fourty',
50 => 'fifty',
60 => 'sixty',
70 => 'seventy',
80 => 'eighty',
90 => 'ninety',
100 => 'hundred',
1000 => 'thousand',
1000000 => 'million',
1000000000 => 'billion',
1000000000000 => 'trillion',
1000000000000000 => 'quadrillion',
1000000000000000000 => 'quintillion',
];
if (!is_numeric($number)) {
throw new \Exception('NaN');
}
if (($number >= 0 && (int) $number < 0) || (int) $number < 0 - PHP_INT_MAX) {
throw new \Exception('numberToWord only accepts numbers between -'.PHP_INT_MAX.' and '.PHP_INT_MAX);
}
if ($number < 0) {
return $negative.self::numberToWord(abs($number));
}
if (strpos($number, '.') !== false) {
list($number, $fraction) = explode('.', $number);
}
switch (true) {
case $number < 21:
$string = $dictionary[$number];
break;
case $number < 100:
$tens = ((int) ($number / 10)) * 10;
$units = $number % 10;
$string = $dictionary[$tens];
if ($units) {
$string .= $hyphen.$dictionary[$units];
}
break;
case $number < 1000:
$hundreds = $number / 100;
$remainder = $number % 100;
$string = $dictionary[$hundreds].' '.$dictionary[100];
if ($remainder) {
$string .= $conjunction.self::numberToWord($remainder);
}
break;
default:
$baseUnit = pow(1000, floor(log($number, 1000)));
$numBaseUnits = (int) ($number / $baseUnit);
$remainder = $number % $baseUnit;
$string = self::numberToWord($numBaseUnits).' '.$dictionary[$baseUnit];
if ($remainder) {
$string .= $remainder < 100 ? $conjunction : $separator;
$string .= self::numberToWord($remainder);
}
break;
}
if (null !== $fraction && is_numeric($fraction)) {
$string .= $decimal;
$words = [];
foreach (str_split((string) $fraction) as $number) {
$words[] = $dictionary[$number];
}
$string .= implode(' ', $words);
}
return $string;
}
Hope some or any of these help out in your programming journeys.