Linux Ask!

Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.

Sep 142010
 

Calculate PHP script's execution time

Answer:

If you want to estimate the PHP script's execution time, you can try something like the following:

<?php

$time_start = microtime(true);

// some long running codes...

$time_end = microtime(true);

echo "Time (msec) passed: " , $time_end - $time_start;
Sep 082010
 

Generate UUID in PHP

Answer:

To generate UUID in PHP, you can try the script below:

<?php

function uuid($prefix = '') {
    $chars = md5(uniqid(mt_rand(), true));
    $uuid  = substr($chars,0,8) . '-';
    $uuid .= substr($chars,8,4) . '-';
    $uuid .= substr($chars,12,4) . '-';
    $uuid .= substr($chars,16,4) . '-';
    $uuid .= substr($chars,20,12);
    return $prefix . $uuid;
}

echo uuid();

It shows something like the following when executed:

c664b9b4-6c44-c8d9-acf9-93ef0e11e435

Sep 062010
 

Clone an object in PHP

Answer:

It is easy to clone an object in PHP, using the following method.

<?php

    $obj = new stdClass(); 
    $obj->foo = "foo";
    $obj->bar = "bar";

    $new_obj = clone $obj;
    var_dump ( new_obj );

It will print out...

object(stdClass)#2 (2) {
  ["foo"]=>
  string(3) "foo"
  ["bar"]=>
  string(3) "bar"
}
Aug 222010
 

Convert array to object in PHP

Answer:

It is easy to cast an object to an array in PHP, using the following method.

<?php

    $obj = new stdClass(); 
    $obj->foo = "foo";
    $obj->bar = "bar";

    var_dump ( (array) $obj );

It will print out...

array(2) {
  ["foo"]=>
  string(3) "foo"
  ["bar"]=>
  string(3) "bar"
}