Tag Archives: function

PHP: Print out all Variables passed to a Function CodeUnit 04 JUN 2010

Working on old scripts can be quite annoying, particularly when you encounter an undocumented function and are trying to figure out firstly which inputs that function accepts, and secondly what it actually then does with it!

Of course, the easiest way of determining this is to call the function and print out what variables are coming into it, and thanks to some native PHP functions, this turns out to be quite the easy thing to do.

First up is func_num_args() which returns the number of arguments passed into the current user-defined function. Then comes the handy func_get_args() which returns an array which contains all the arguments (corresponding to the user-defined function’s argument list) passed into the function. Finally, func_get_arg() is used to return a specified argument from the passed in arguments, starting from a zero index.

If we grab a test argument to show all of the above functions in action, we get this: (grabbed off the main PHP documentation site)

function foo()
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs
n"; if ($numargs >= 2) { echo "Second argument is: " . func_get_arg(1) . "
n"; } $arg_list = func_get_args(); for ($i = 0; $i < $numargs; $i++) { echo "Argument $i is: " . $arg_list[$i] . "
n"; } } foo(1, 2, 3);

Quite handy little functions, aren’t they?

(And to think that I didn’t even know of their existence up until now! :P)

PHP: Implode a Multi-dimensional Array CodeUnit 09 APR 2010

PHP’s implode is a pretty handy function to flatten any array into a single string value, using any piece of ‘glue’ (basically a substring) that you specifiy to put everything together.

So in other words, if we had an array containing the string values of cat, dog and chicken and then ran the implode function against them using the character ‘|’ as glue, we would end up with a single string value reading cat | dog | chicken.

Of course, extending this function to handle multi-dimensional arrays (or matrices if you prefer) is a pretty simple matter of quickly whipping up a recursive version and so without any further waffling from my side, here’s the code:

//flattens a multi-dimensional array (recursive implode)
//-----------------------------------------------------------
function r_implode( $glue, $pieces )
{
	foreach( $pieces as $r_pieces )
	{
    		if( is_array( $r_pieces ) )
    		{
      			$retVal[] = r_implode( $glue, $r_pieces );
    		}
    		else	
    		{
      			$retVal[] = $r_pieces;
    		}
  	}
  	return implode( $glue, $retVal );
} 
//-----------------------------------------------------------

Usage is pretty simple. Call the r_implode function as normal, passing to it the ‘glue’ string you wish to employ as well as the array against which to run it.

Have fun.

Get the Last Day of a Month using PHP CodeUnit 27 MAR 2010

Picked this cool little PHP function to calculate and return the last day of a month for any year off the always informative lutrov interactive website the other day, and posted it here for future reference – because that’s just how I roll! ;)

Anyway, here goes:

function lastday($month = '', $year = '',$format = 'Y-m-d') {
   if (empty($month)) {
      $month = date('m');
   }

   if (empty($year)) {
      $year = date('Y');
   }

   $result = strtotime("{$year}-{$month}-01");
   $result = strtotime('-1 second', strtotime('+1 month', $result));

   return date($format, $result);
}

As you can see, usage is a simple matter of calling lastday() and feeding it the year and month you want it to return the last day for, though if you leave these two parameters out, it will simply return you the last date of the current month – all in a handy ISO 8601 formatting.

Useful.

PHP: Convert a UTF-16 String to a UTF-8 String CodeUnit 05 MAR 2010

Andrew Walker crafted this handy little PHP function which can convert a UTF-16 encoded string into a more PHP-friendly UTF-8 encoded string.

The function first checks to see if the string passed to it is prefixed with a Byte Order Mark (BOM), and if the necessary BOM exists, the function continues to convert the rest of the string to its more compact UTF-8 format.

Obviously if no BOM is present, the function leaves the input string unchanged.

function utf16_to_utf8($str) {
    $c0 = ord($str[0]);
    $c1 = ord($str[1]);

    if ($c0 == 0xFE && $c1 == 0xFF) {
        $be = true;
    } else if ($c0 == 0xFF && $c1 == 0xFE) {
        $be = false;
    } else {
        return $str;
    }

    $str = substr($str, 2);
    $len = strlen($str);
    $dec = '';
    for ($i = 0; $i < $len; $i += 2) {
        $c = ($be) ? ord($str[$i]) << 8 | ord($str[$i + 1]) : 
                ord($str[$i + 1]) << 8 | ord($str[$i]);
        if ($c >= 0x0001 && $c <= 0x007F) {
            $dec .= chr($c);
        } else if ($c > 0x07FF) {
            $dec .= chr(0xE0 | (($c >> 12) & 0x0F));
            $dec .= chr(0x80 | (($c >>  6) & 0x3F));
            $dec .= chr(0x80 | (($c >>  0) & 0x3F));
        } else {
            $dec .= chr(0xC0 | (($c >>  6) & 0x1F));
            $dec .= chr(0x80 | (($c >>  0) & 0x3F));
        }
    }
    return $dec;
}

Thanks Andrew, this was exactly what I was looking for! :)

Related Link: http://www.moddular.org/log/utf16-to-utf8