Time Ago Function in PHP

Here’s a lightweight PHP function which accepts a date as a parameter and converts it into “sometime age” output.

Read Also: How to enable mod_rewrite in Ubuntu

function time_ago($date) {
    if (empty($date)) {
        return "Please enter a date!";
    $duration_in = [
    $len = [
    $now = time();
    $unixDate = strtotime($date);

    if (empty($unixDate)) {
        return "Please enter a valid date!";

    if ($now > $unixDate) {
        $diff = $now - $unixDate;
        $tense = "ago";
    } else {
        $diff = $unixDate - $now;
        $tense = "from now";
    for ($j = 0; $diff >= $len[$j] && $j < count($len) - 1; $j++) {
        $difference /= $len[$j];
    $diff = round($diff);
    if ($diff != 1) {
        $duration_in[$j].= "s";
    return "$diff $duration_in[$j] {$tense}";


echo time_ago($date);

Source: http://stackoverflow.com/a/18891474

How to convert a negative number to a positive number using PHP

PHP comes with a built-in function called abs() [Absolute Value] to convert a negative number to positive number. It accepts one parameter the number itself. The number can be a integer or a float. If the parameter supplied to the function is float it will return float value. Otherwise, it will return an integer.

Changing AngularJS templating brackets


echo abs(-6.2);  // 6.2 (float)
echo abs(19);    // 19 (integer)
echo abs(-2);    // 2 (integer)


How To Remove Last Comma From String Using PHP?

Generally, developers use loops to create a comma separated lists in string format. But, after the loop you end with a trailing comma at the end of the string.

Useful Read : Export the MySQL database table as CSV format using PHP

To remove this comma we are going to use PHP’s built rtrim function. rtrim function is used to strip off whitespaces and predefined characters from right side of the string. It accepts two parameters,

  1. String – String we want to trim (Required)
  2. Character – Characters which we want to strip (Optional)

Here’s an example code:

$string = "a, b, c, d,";
$filtered = rtrim($string, ',');
echo $filtered;

As you can, we are passing a variable with a comma separated list and a comma(,) as second parameter. The output of above code is as follows.

a, b, c, d


How to get youtube video ID from url using php?

Here’s a handy PHP code snippet which allows you to extract the video ID of a YouTube video from URL. All you need to do is pass the YouTube URL to the getYouTubeId() function.

Quick Tip : Unzip a file with php

//get video id from youtube url
function getYouTubeId($url){
	parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
	return $my_array_of_vars['v'];
echo getYouTubeId('https://www.youtube.com/watch?v=y2Ky3Wo37AY');

The Above code will output,