Showing entries with tag "PHP".

Found 12 entries

PHP: Look in to a multi-dimensional array using array_dive()

I have a multi-dimensional array that I need to extract data from. Given a string in the format of "person.first" I want to descend in to the array looking for person -> first. I wrote this array_dive() function to facilitate this lookup.

function array_dive(string $needle, array $haystack) {
    // Split at the periods
    $parts = explode(".", $needle);

    // Loop through each level of the hash looking for elem
    $arr = $haystack;
    foreach ($parts as $elem) {
        //print "Diving for $elem<br />";
        $arr = $arr[$elem] ?? null;

        // If we don't find anything stop looking
        if ($arr === null) {

    // If we find a scalar it's the end of the line, anything else is just
    // another branch, so it doesn't cound as finding something
    if (is_scalar($arr)) {
        $ret = $arr;
    } else {
        $ret = null;

    return $ret;

Here is a sample script that shows the function in action.

Leave A Reply

PHP: Sanitize a string down to printable characters

I needed a function to make strings into usuable URL identifiers. This function will take an input string and replace all non-url friendly characters with underscores.

function string_sanitize(string $str) {
    // Replace any non-word chars with underscores
    $str = preg_replace("/[\W_]+/", "_", $str);
    // Remove any leading/trailing underscores that are leftover
    $str = trim($str, "_");

    return $str;
Leave A Reply

PHP: Convert an array to a hash

I have a flat array that I want to convert to a hash so I can use it as a lookup table. There isn't an easy or clear way to do that in PHP so I wrote my own function:

function array_to_hash(array $array, $val = 1) {
    $ret = array_fill_keys($array, $val);

    return $ret;
Leave A Reply

PHP: Calculate the percentage difference between two numbers

I need to compare two numbers and see if they're close to each other. Specifically I wanted to see if two numbers were within 3% of of each other. I wrote this simple function to calculate the percentage difference between two numbers, and optionally (with the third parameter) return true or false if they're within a given range. This should allow me to do a "fuzzy compare" on two numbers.

function percent_diff($a, $b, $ok_per = null) {
    $per_diff = abs((1 - ($a / $b)) * 100);

    if (is_numeric($ok_per)) {
        $ok = $per_diff < $ok_per;

        return $ok;

    return $per_diff;
Leave A Reply

PHP: Disable output buffering for the CLI

When writing a PHP application that's going to be run from the CLI often you will want to disable output buffering. With output buffering enabled you will not see any output until your terminal buffer (usually 1k or 4k) fills up . This is accomplished with the following PHP code at the beginning of your script:

Leave A Reply

PHP: IPV6 reverse DNS entries

Reverse DNS (PTR) entries in IPV6 are different than their IPV4 counterparts. To create an IPV6 reverse entry, you have to: fully expand the address, reverse it, and add a period between each character.

For example: 2001:db8::60 reverses to

I wrote a simple PHP function to handle this for me:

function ipv6_ptr($ip_str) {
    $hex = unpack("H*hex", inet_pton($ip_str));
    $str = strrev($hex['hex']);
    $p   = str_split($str);
    $ret = join(".",$p);

    return $ret;
Leave A Reply

PHP: is_exception()

I have an object in PHP that I need to check if it is an exception and act appropriately. Surprisingly PHP does not have an is_exception() function built in so I had to write my own:

function is_exception($obj,$strict = false) {
    if (!is_object($obj)) {
        return false;

    // It's some type of exception
    if ($obj instanceof Exception) {
        if (!$strict) {
            return true;
        // It's a raw exception
        } elseif (get_class($obj) === "Exception") {
            return true;

    return false;

If you pass true as the second parameter it will only return true if it's a raw exception and not an inherited exception.

Leave A Reply

PHP: Relative path between two directories

I need to calculate the relative path between two directories such that:

$a = "/one/two/three/four/";
$b = "/one/two/";

$a to $b has a relative path of ../../ and $b to $a has a relative path of three/four/. This function solves that problem very simply:

// Borrowed from and cleaned up
function relativePath($from, $to, $ps = DIRECTORY_SEPARATOR) {
    $arFrom = explode($ps, rtrim($from, $ps));
    $arTo   = explode($ps, rtrim($to, $ps));

    while(count($arFrom) && count($arTo) && ($arFrom[0] == $arTo[0])) {

    return str_pad("", count($arFrom) * 3, '..' . $ps) . implode($ps, $arTo);
Leave A Reply

PHP: flat_var_export()

I needed to log a nested array to a file. To do this I needed to convert the array to a single line. After some searching I found improved_var_export() that converts a PHP array/object to a single line textual representation. I cleaned up some of the formatting and this is the result.

function flat_var_export($variable, $return = false) {
    if ($variable instanceof stdClass) {
        $result = '(object) ' . flat_var_export(get_object_vars($variable), true);
    } elseif (is_array($variable)) {
        $array = array();
        foreach ($variable as $key => $value) {
            $array[] = var_export($key, true) . ' => ' . flat_var_export($value, true);
        $result = 'array(' . implode(', ', $array) . ')';
    } else {
        $result = var_export($variable, true);

    if ($return) {
        return $result;
    } else {
        print $result;
Leave A Reply

PHP: Quote Word

I needed a function similar to Perl's qw. If you pass a string to this function it will return an array of the words, stripping any separating whitespace. If you pass true as the second parameter you will instead get a hash returning each word in a key/value pair.

function qw($str,$return_hash = false) {
    $str = trim($str);

    // Word characters are any printable char
    $words = str_word_count($str,1,"!\"#$%&'()*+,./0123456789-:;<=>?@[\]^_`{|}~");

    if ($return_hash) {
        $ret = array();
        $num = sizeof($words);

        // Odd number of elements, can't build a hash
        if ($num % 2 == 1) {
            return array();
        } else {
            // Loop over each word and build a key/value hash
            for ($i = 0; $i < $num; $i += 2) {
                $key   = $words[$i];
                $value = $words[$i + 1];

                $ret[$key] = $value;

            return $ret;
    } else {
        return $words;

This is useful in the following scenarios:

$str  = "Leonardo    Donatello    Michelangelo    Raphael";
$tmnt = qw($str);

$str = "
    Leonardo       Blue
    Donatello      Purple
    Michelangelo   Orange
    Raphael        Red
$turtles = qw($str,true);
Leave A Reply

Regexp for spliting on non-escaped characters

I have a string like the following:

desc=Did you know 2 + 2 \= 4?

I want to split each chunk of that string into segments separated by the equal signs. I can't just split on the equal signs because the text has an equal sign in it. I need to split on the non-escaped equal signs.

@parts = split(/(?<!\\)=/,$str);

This is called positive and negative look behind.

In PHP the only difference is that you have to double escape your \

$parts = preg_split('/(?<!\\\\)=/',$str);
Leave A Reply

Perlfunc: pfile()

PHP has a handy function named file() that will read the contents of a file into a variable. I wrote a quick Perl version of the same function.

sub pfile {
    my $target = shift();
    my $is_fh  = defined(fileno($target));
    my $ret;

    # If we passed in a FH read everything from that
    if ($is_fh) {
        while (readline($target)) { $ret .= $_; }
    # Else it's a file to be opened 
    } else {
        open (my $fh, "<", $target) or return undef;

        while (<$fh>) { $ret .= $_; }

    if (wantarray) {
        return split('\n',$ret);

    return $ret;
Leave A Reply - 1 Reply