em411 / Useful PHP functions

Created Fri, 12 Aug 2022 00:00:00 +0000 Modified Fri, 12 Aug 2022 00:00:00 +0000
488 Words

checkdnsrr()

With this function you can check the DNS records for an IP or hostname that you can pass to the function as a param. A really good use case is to check if the domain of a given email address exists.

<?php

function validateMail(string $email): bool
{
    $parts = explode("@", $email);
    $host = end($parts);
    return checkdnsrr($host, 'MX');
}

$email = '[email protected]';

validateMail($email);

This helps you to avoid bounce emails trying to create an account on your website or platform.

extract()

Extract variables from a given array into the current symbol table, which means you can access the array values as variables in your ongoing program. A symbol table reflects a scope which basically maps your PHP code variables to the internal Zend Engine values(ZVAL).

One issue with the extract function is that you need to be very careful with this function. If you apply it with $_GET to automatically inject variables you might inject unsanitized user input leading to malicious software. It’s recommended to use the EXTR_SKIP constant to not override variables in the current symbol table.

<?php

$a = 'oldValue';

extract(
    [
        'a' => 'test',
        'b' => 'foo'
    ],
    EXTR_SKIP
);

printf("%s => %s", $a, $b);

func_get_args()

You can find this function used often in code that generates a hash key to store a value in an in-memory cache(Redis, Memcached). So you can take the params passed to a data retrieval function with func_get_args and build a cache key to check and update your in-memory cache with data from an external service:

<?php

function getProductData(int $productId, string ... $predicates)
{
    $args = func_get_args();
    $hash = '';
    foreach ($args as $arg){
        $hash .= (string)($arg);
    }

    $cacheKey = md5($hash);

    //@todo -> fetch data form external service on cache miss and update the cache
}

array_column()

A really common usecase which I faced a lot is to extract one value from a two dimensional array into a flat array. This can be easily done with the array_column function. In the following example, we want a flattened array with the age value only:

<?php

$array = [
    [
        'name' => 'Misty',
        'age' => 15
    ],
    [
        'name' => 'Charlie',
        'age' => 40
    ]
];

var_dump(array_column($array, 'age'));

levenshtein()

The levenshtein distance computes the difference between two strings. It counts the number of how much characters needs to be added, replaced or deleted to get from one string to the comparable one:

<?php
$lev = levenshtein($subname, $parts[$i]);
if ($lev <= \strlen($subname) / 3 || '' !== $subname && false !== strpos($parts[$i], $subname)) {
    $alternatives[$collectionName] = $exists ? $alternatives[$collectionName] + $lev : $lev;
} elseif ($exists) {
    $alternatives[$collectionName] += $threshold;
}

So if a user passes a typo as input to your command, you can try to match the user input and suggest the closest string by utilizing the levenshtein distance. You can find this usage in the symfony framework to suggest a command name if it couldn’t find it by your input: