Me Favorite PHP Functions

Just a small collection of some of my favorite PHP functions I tend to use and re-use in my Code Canyon Projects.

Check an array for a specific VALUE

/*
 * Function to check an array for a specific value
 *
 * @param string $val         The value to search for
 * @param var $arr            The array to search
 * @return true/false         Boolen
 */
function checkArray($val, $arr) {
    if (in_array($val, $arr)) {
        return true;
    }
    foreach($arr as $k) {
        if (is_array($k) && checkArray($val, $k)) {
            return true;
        }
    }
    return false;
}

Generate SEO Friendly URL Slugs

/*
 * Function to generate SEO Friendly URL Slugs
 * Ie.: This is an Article Title => this-is-an-article-title
 *
 * @param     string $val           The String to convert
 * @return    string $val           The SEO Friendly URL
 */
function seoString($val) {
    $val = trim($val);
    $val = html_entity_decode($val);
    $val = strip_tags($val);
    $val = strtolower($val);
    $val = preg_replace('~[^ a-z0-9_.]~', ' ', $val);
    $val = preg_replace('~ ~', '-', $val);
    $val = preg_replace('~-+~', '-', $val);

    return $val;
}

Generate Hyperlinks

/*
 * Function to generate Hyperlinks
 *
 * @param     string $val The String to convert to a clickable Hyperlink
 * @return     string $val    The Hyperlink URL
 */
function linkUrls($val){
    return preg_replace('!(((f|ht)tp(s)?://)[-a-zA-Zа-яА-Я()0-9@:%_+.~#?&;//=]+)!i', '<a href="$1" target="_blank">$1</a>', $val);
}

Ellipse-ify text to a specific length

/*
 * Function to ellipse-ify text to a specific length
 *
 * @param string $text      The text to be ellipsified
 * @param int    $max       The maximum number of characters (to the word) that should be allowed
 * @param string $append    The text to append to $text
 * @return string           The shortened text
 */
function ellipsis($text, $max = '', $append = '&hellip;') {
    if (strlen($text) <= $max) {
        return $text;
    }

    $replacements = array(
        '|<br /><br />|' => ' ',
        '|&nbsp;|' => ' ',
        '|&rsquo;|' => '\'',
        '|&lsquo;|' => '\'',
        '|&ldquo;|' => '"',
        '|&rdquo;|' => '"',
    );

    $patterns = array_keys($replacements);
    $replacements = array_values($replacements);

    // Convert double newlines to spaces.
    $text = preg_replace($patterns, $replacements, $text);

    // Remove any HTML.  We only want text.
    $text = strip_tags($text);

    $out = substr($text, 0, $max);
    if (strpos($text, ' ') === false) {
        return $out.$append;
    }

    return preg_replace('/(\W)&(\W)/', '$1&amp;$2', (preg_replace('/\W+$/', ' ', preg_replace('/\w+$/', '', $out)))).$append;
}

Filter profanity words

This function uses Fontawesome.

/*
 * Functions to filter profanity words
 * Replace profanity word with FontAwesome asterisks
 *
 * @param string    $text            The text to be filtered
 * @array           $filterWords    The profanity to filter for
 * @variable        $filterCount    The character length of the profanity word
 * @return string                    The filtered text
 */
$badWords = 'List,of,bad,words,seperated,with,commas';

function filterwords($text) {
    global $badWords;

    $filterCount = sizeof($badWords);
    for($i = 0; $i < $filterCount; $i++) {
        $text = @preg_replace('/\b'.preg_quote($badWords[$i]).'\b/ie',"str_repeat('<i class=\"fa fa-asterisk filtered\"></i>',strlen('$0'))",$text);
    }
    return $text;
}

Format future dates into "Days Until"

/*
 * Function to format Dates into "Days Until"
 *
 * @param string $v The database value (ie. 2014-10-31)
 * @return string The formatted Date in Days Until
 */
function daysUntil($v){
    return (isset($v)) ? floor((strtotime($v) - time())/60/60/24) : FALSE;
}

convert Dates into Time Ago

/*
 * Function to convert Dates into Time Ago
 *
 * @param string $date      The database value (ie. 2014-10-31)
 * @return string           The formatted Date in Days Ago
 */
function timeago($date) {
    if (empty($date)) {
        return "";
    }
    $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
    $lengths = array("60","60","24","7","4.35","12","10");

    $now = time();
    $unix_date = strtotime($date);

    // check validity of date
    if (empty($unix_date)) {
        return "";
    }

    // is it future date or past date
    if ($now > $unix_date) {
        $difference = $now - $unix_date;
        $tense = "ago";
    } else {
        $difference = $unix_date - $now;
        $tense = "from now";
    }

    for ($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
        $difference /= $lengths[$j];
    }

    $difference = round($difference);

    if ($difference != 1) {
        $periods[$j].= "s";
    }

    return "$difference $periods[$j] {$tense}";
}

List all files in a given directory

/*
 * Function to list all files in a given directory
 *
 * @param string $dir The directory to search
 * @return $res The list of files
 */
function listFiles($dir) {
    $root = scandir($dir);
    foreach ($root as $value) {
        if ($value === '.' || $value === '..') {
            continue;
        }
        if (is_file("$dir/$value")) {
            $res[] = "$dir/$value";
            continue;
        }
        foreach (listFiles("$dir/$value") as $value) {
            $res[] = $value;
        }
    }
    if (isset($res)) {
        return $res;
    }
}

Calculate a file's size

/*
 * Function to calculate a file's size
 *
 * @param string $file The file
 * @param string $type The size type (KB. MB, GB)
 * @return $filesize The formated file size
 */
function formatbytes($file, $type) {
    switch ($type) {
        case 'KB':
        $filesize = filesize($file) * .0009765625;
        break;
        case 'MB':
        $filesize = (filesize($file) * .0009765625) * .0009765625;
        break;
        case 'GB':
        $filesize = ((filesize($file) * .0009765625) * .0009765625) * .0009765625;
        break;
        default: break;
    }

    if ($filesize <= 0) {
        return $filesize = 'unknown';
    } else {
        return round($filesize, 2).' '.$type;
    }
}

calculate total days between two dates

/*
 * Function to calculate total days between two dates
 */
function datediff($interval, $datefrom, $dateto, $using_timestamps = false) {
    /*
        $interval can be:
          yyyy  - Number of full years
          q     - Number of full quarters
          m     - Number of full months
          y     - Difference between day numbers (eg 1st Jan 2004 is "1", the first day. 2nd Feb 2003 is "33". The datediff is "-32".)
          d     - Number of full days
          w     - Number of full weekdays
          ww    - Number of full weeks
          h     - Number of full hours
          n     - Number of full minutes
          s     - Number of full seconds (default)
    */

    if (!$using_timestamps) {
        $datefrom = strtotime($datefrom, 0);
        $dateto = strtotime($dateto, 0);
    }

    // Difference in seconds
    $difference = $dateto - $datefrom;

    switch($interval) {
        case 'yyyy':
            $years_difference = floor($difference / 31536000);
            if (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom), date("j", $datefrom), date("Y", $datefrom)+$years_difference) > $dateto) {
                $years_difference--;
            }
            if (mktime(date("H", $dateto), date("i", $dateto), date("s", $dateto), date("n", $dateto), date("j", $dateto), date("Y", $dateto)-($years_difference+1)) > $datefrom) {
                $years_difference++;
            }
            $datediff = $years_difference;
        break;
        case "q":
            $quarters_difference = floor($difference / 8035200);
            while (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom)+($quarters_difference*3), date("j", $dateto), date("Y", $datefrom)) < $dateto) {
                $months_difference++;
            }
            $quarters_difference--;
            $datediff = $quarters_difference;
        break;
        case "m":
            $months_difference = floor($difference / 2678400);
            while (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom)+($months_difference), date("j", $dateto), date("Y", $datefrom)) < $dateto) {
                $months_difference++;
            }
            $months_difference--;
            $datediff = $months_difference;
        break;
        case 'y':
            $datediff = date("z", $dateto) - date("z", $datefrom);
        break;
        case "d":
            $datediff = floor($difference / 86400);
        break;
        case "w":
            $days_difference = floor($difference / 86400);
            $weeks_difference = floor($days_difference / 7); // Complete weeks
            $first_day = date("w", $datefrom);
            $days_remainder = floor($days_difference % 7);
            $odd_days = $first_day + $days_remainder; // Do we have a Saturday or Sunday in the remainder?

            // Sunday
            if ($odd_days > 7) {
                $days_remainder--;
            }

            // Saturday
            if ($odd_days > 6) {
                $days_remainder--;
            }

            $datediff = ($weeks_difference * 5) + $days_remainder;
        break;
        case "ww":
            $datediff = floor($difference / 604800);
        break;
        case "h":
            $datediff = floor($difference / 3600);
        break;
        case "n":
            $datediff = floor($difference / 60);
        break;
        default:
            $datediff = $difference;
        break;
    }

    return $datediff;
}

Hope these help others out there. If you have any questions or comments, please leave a comment below. I would love to hear feedback about my favorite PHP functions.