Searched for "function" and found 13 matches in 0 seconds





PHP: Stopwatch function to time pieces of code

I need to time how long a certain piece of code takes to complete. I wrote a simple PHP stopwatch function to accomplish this:

sw(); // Start the stopwatch
$x  = some_slow_code();
$ms = sw(); // Return milliseconds since start
// Stopwatch function: returns milliseconds
function sw() {
    static $start = null;

    if (!$start) {
        $start = hrtime(1);
    } else {
        $ret   = (hrtime(1) - $start) / 1000000;
        $start = null; // Reset the start time
        return $ret;
    }
}
Leave A Reply

PHP: Either function because PHP lacks a good "or"

PHP lacks a good "or" comparison operator. Neither the or operator, nor the || return a value. I wrote a function that will take two (or more) variables and return the first one that has a non-empty value.

$limit = $array_count || 15;       // true (bad!)
$limit = $array_count or 15;       // true (also bad!)
$limit = either($array_count, 15); // 15 (good!)
function either() {
    $items = func_get_args();

    // Return the first non-empty item
    foreach ($items as $x) {
        if (!empty($x)) {
            return $x;
        }
    }

    return null;
}
Leave A Reply

PHP Function: linkify

I needed a function to take a chunk of text and turn all the URLs inside of it to hyperlinks. Here is the solution I came up with:

function linkify($str) {
    $new_str = preg_replace("@[http|https|ftp]+://[^<>[:space:]]+[[:alnum:]/]@","<a href=\"\\0\">\\0</a>", $str);
    return $new_str;
}
Leave A Reply

Internet Explorer has a broken split function

I just spent several hours working on an Internet Explorer issue. I seems Internet Explorer does NOT include empty elements in the results of a split. Browser brokeness with relation to the split function is well documented. If you have a string:

var txt = "a|b||c||d|e|f";

and you split on the | character you would expect eight pieces. Internet Explorer will only give you six pieces instead of eight because the 3rd and 5th elements are null strings. The problem is compounded if your string starts or ends with a | character.

Note: looks like this is fixed in IE9.

Leave A Reply

PHP function to test if an IP is an IPV6 address

This function will tell you if an IP address is a valid IPV6 address.

function is_ipv6($ip) {
    // If it contains anything other than hex characters, periods, colons or a / it's not IPV6
    if (!preg_match("/^([0-9a-f\.\/:]+)$/",strtolower($ip))) { return false; }

    // An IPV6 address needs at minimum two colons in it
    if (substr_count($ip,":") < 2) { return false; }

    // If any of the "octets" are longer than 4 characters it's not valid
    $part = preg_split("/[:\/]/",$ip);
    foreach ($part as $i) { if (strlen($i) > 4) { return false; } }

    return true;
}
Leave A Reply

bash function epoch_days

I needed to calculate days since the epoch. I wrote up a quick bash function to do the math for me.

function epoch_days() { 
    time=$(date --utc +%s);
    day=86400;
    days=$(( $time / $day ));

    echo $days;
}
Leave A Reply

Caching results in a PHP function

If you have a function that will get called lots of times, and you'd like to cache the results so as not to incur a performance penalty for hitting the disk/DB again use static variables.

function get_user($id) {
  // Sanitize the input
  $id = intval($id);

  // Declaring as static prevents the variable from dying when the function exits
  static $cache;

  // If the data is already in the cache just return that
  if ($cache[$id]) { return $cache[$id]; }

  // Get the data from the DB/Disk/Slow Source
  $rs = mysql_query("SELECT * FROM UserTable WHERE ID = $id");
  $ret = mysql_fetch_assoc($rs);

  // Store the results in the cache so it will be there next time
  $cache[$id] = $ret;

  return $ret;
}

This will store the results in cache (memory), speeding up subsequent requests. This cache will last until your script ends. To store across multiple script executions you'll want to look at something like memcache.

Leave A Reply - 1 Reply

PHP functions in JS

What a great idea!
PHP.JS is an open source project in which we try to port PHP functions to JavaScript. By including the PHP.JS library in your own projects, you can use your favorite PHP functions client-side. - phpjs.org
Leave A Reply

PHP Function long_line

This function should split a long line at a specified width. Preserving words, only splitting at spaces.

function long_line($line,$chars,$debug=0) { if ($debug) { print "processing: $line<br />\n"; } $ret = substr($line,0,$chars); $count = $chars; while ($char != " ") { $char = substr($line,$count,1); if ($char == '') { return $ret; } if ($debug) { print "$count: '$char'<br />\n"; } $ret .= $char; $count++; } $ret .= "<br />\n"; $mystr = substr($line,$count); $ret .= long_line($mystr,$chars,$debug); return $ret; }
Leave A Reply - 2 Replies

Perl Function: random_mac()

Function to generate a random MAC address. Just for testing.

sub random_mac() { my ($mac,$i); for ($i=0;$i<6;$i++) { $mac .= zeropad(sprintf("%x",rand() * 255)) . ":"; } $mac = substr($mac,0,length($mac)-1); return $mac; }
Leave A Reply

Perl Function: mac2char

Function to convert a mac to a 6 byte string. Warning: it's nor a printable string.

sub mac2char() { my $mac = shift(); if ($mac !~ /w[-:]w[-:]w[-:]w[-:]w[-:]w/) { print "n$mac not a valid mac addressn"; return 0; } my @chars = split(/[:-]/,$mac); my $ret; foreach (@chars) { $ret .= chr(hex($_)); } return $ret; } sub char2mac() { my $chars = shift(); my $sep = shift(); my (@ret,$ret,$i); $sep ||= ":"; for ($i=0;$i<6;$i++) { my $char = substr($chars,$i,1); $octet = sprintf("%x",(ord($char))); $octet = &zeropad($octet); push(@ret,$octet); #push(@ret,$char); } return join($sep,@ret); }
Leave A Reply

Functions

I'm writing functions for everything on this page in an attempt to make it more modular.  I had some much stuff hardcoded into it the first time I went through it.  Makes updating things a pain!
Leave A Reply

PHP Function

There is a PHP function called ip2long, and one called long2ip. Pretty cool function. It stores an IP address (16 byte string) as a 4 byte long. Pretty cool if you have to store a lot of IP addresses in a database. So I have learned something from my new book!
Leave A Reply