Saturday, August 24, 2013

Calendar Script PHP

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/



$day = date('j'); //what day is it today
$month = date('n'); //what month are we in?
$year = date('Y'); //what year are we in?

//get the first first day of the month
$first_day_of_month = date('w',mktime(1,1,1,$month,1,$year));

$days_in_month = date('t'); //how many days in this month

print "SU\tMO\tTU\tWE\tTH\tFR\tSA
"; //print the weekday headers //count ahead to the weekday of the first day of the month for ($spacer = 0; $spacer < $first_day_of_month; $spacer++) { print "  \t"; } for ($x = 1; $x <= $days_in_month; $x++) { //begin our main loop //if we have gone past the end of the week, go to the next line if ($spacer >= 7) { print "
"; $spacer = 0; } //if the length of the current day is one, put a "0" in front of it if (strlen($x) == 1) { $x = "0$x"; } if ($x == $day) { //is this day the current day print "$x\t"; //if so put an indicator } else { print "$x\t"; //otherwise just print it } $spacer++; //increment our spacer } ?>

Square Roots in PHP

Doing square roots in PHP is really simple, all you need to do is to call the function sqrt().  Lets see some code.
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

//Set number you would like to take square root
$int = 9;
//Take square root
$sqrt = sqrt($int);
//Display result
echo $sqrt;


?>
As you can see, simple to do. Now lets do it in a more mathematical way using the PHP function pow(), which is the power function. pow() has two inputs, pow($base, $n). $base is the base number you will raise to the $n power. Now usually, we would use this function to calculate powers like 22 (which is 4). However, if you know your math, we can raise numbers to the power of fractions, which is the same as taking the root of numbers. Not just the square root either, we can use this to find the cube root, fourth root, any root you would like to find. Now lets see some code for finding the cube root of 729.

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

//Set base number and the exponent
$base = 729;
$exp = 1/3;
//Take root
$sqrt = pow($base, $exp);
//Display result
echo $sqrt;


?>
The $base is the number we will be taking the power of $exp of. This way we can use the pow() function to not only find powers of numbers but the roots as well.



Other notes:

All PHP code needs “<?php” before and “?>” after the code to run.

The double slash “//” is a comment that PHP will ignore. For bigger comments, use “/* really big comment */”.

The “$int” is a variable. Use the dollar sign in front of a meaningful variable name to create variables in PHP.

sqrt() is the function that calculates the square root of a float number.

pow($float, $exp) is the function calculates a number $float to the power of $exp.

The “echo” function prints whatever values you pass to it in the HTML of the webpage.

Saturday, August 17, 2013

Convert bytes to B, KB, MB, GB, TB, PB, EB, ZB, YB

Simple PHP function that formats the bytes to the desired form. Possible unit options are:

Byte (B)
Kilobyte (KB)
Megabyte (MB)
Gigabyte (GB)
Terabyte (TB)
Petabyte (PB)
Exabyte (EB)
Zettabyte (ZB)
Yottabyte (YB)

Function takes three parameter: (bytes mandatory, unit optional, decimals optional):



<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

function byteFormat($bytes, $unit = "", $decimals = 2) {
 $units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 
   'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8);
 
 $value = 0;
 if ($bytes > 0) {
  // Generate automatic prefix by bytes 
  // If wrong prefix given
  if (!array_key_exists($unit, $units)) {
   $pow = floor(log($bytes)/log(1024));
   $unit = array_search($pow, $units);
  }
 
  // Calculate byte value by prefix
  $value = ($bytes/pow(1024,floor($units[$unit])));
 }
 
 // If decimals is not numeric or decimals is less than 0 
 // then set default value
 if (!is_numeric($decimals) || $decimals < 0) {
  $decimals = 2;
 }
 
 // Format output
 return sprintf('%.' . $decimals . 'f '.$unit, $value);
  }


?>
 Usage
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

echo byteFormat(4096, "B") ."\n";
echo byteFormat(8, "B", 2) . "\n";
echo byteFormat(1, "KB", 5) . "\n";
echo byteFormat(1073741824, "B", 0) . "\n";
echo byteFormat(1073741824, "KB", 0) . "\n";
echo byteFormat(1073741824, "MB") . "\n";
echo byteFormat(1073741824) . "\n";
echo byteFormat(1073741824, "TB", 10) . "\n";
echo byteFormat(1099511627776, "PB", 6) . "\n";



?>

PHP Memory Usage


This is a simple example of a class, which can be used to collect the PHP script memory usage information and to print all information.


PHP Memory Usage - Class

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

 class MemoryUsageInformation {
    private $real_usage;
    private $statistics = array();
 
    // Memory Usage Information constructor
    public function __construct($real_usage = false) {
      $this->real_usage = $real_usage;
    }
 
    // Returns current memory usage with or without styling
    public function getCurrentMemoryUsage($with_style = true) {
      $mem = memory_get_usage($this->real_usage);
      return ($with_style) ? $this->byteFormat($mem) : $mem;
    }
 
    // Returns peak of memory usage
    public function getPeakMemoryUsage($with_style = true) {
      $mem = memory_get_peak_usage($this->real_usage);
      return ($with_style) ? $this->byteFormat($mem) : $mem;
    }
 
    // Set memory usage with info
    public function setMemoryUsage($info = '') {
      $this->statistics[] = array('time' => time(), 
                                  'info' => $info, 
                                  'memory_usage' => $this->getCurrentMemoryUsage());
    }
 
    // Print all memory usage info and memory limit and 
    public function printMemoryUsageInformation() {
      foreach ($this->statistics as $satistic) {
        echo  "Time: " . $satistic['time'] . 
              " | Memory Usage: " . $satistic['memory_usage'] . 
              " | Info: " . $satistic['info'];
        echo "\n";
      }
      echo "\n\n";
      echo "Peak of memory usage: " . $this->getPeakMemoryUsage();
      echo "\n\n";
    }
 
    // Set start with default info or some custom info
    public function setStart($info = 'Initial Memory Usage') {
      $this->setMemoryUsage($info);
    }
 
    // Set end with default info or some custom info
    public function setEnd($info = 'Memory Usage at the End') {
      $this->setMemoryUsage($info);
    }
 
    // Byte formatting
    private function byteFormat($bytes, $unit = "", $decimals = 2) {
     $units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 
       'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8);
 
     $value = 0;
     if ($bytes > 0) {
      // Generate automatic prefix by bytes 
      // If wrong prefix given
      if (!array_key_exists($unit, $units)) {
       $pow = floor(log($bytes)/log(1024));
       $unit = array_search($pow, $units);
      }
 
      // Calculate byte value by prefix
      $value = ($bytes/pow(1024,floor($units[$unit])));
     }
 
     // If decimals is not numeric or decimals is less than 0 
     // then set default value
     if (!is_numeric($decimals) || $decimals < 0) {
      $decimals = 2;
     }
 
     // Format output
     return sprintf('%.' . $decimals . 'f '.$unit, $value);
    }
  }



?>
Usage of  Class
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

 // Create new MemoryUsageInformation class
  $m = new MemoryUsageInformation(true);
 
  // Set start
  $m->setStart();
 
  // Create example array
  $a = array();
 
  // Set memory usage before loop
  $m->setMemoryUsage('Before Loop');
 
  // Fill array with
  for($i = 0; $i < 100000; $i++) {
    $a[$i] = uniqid();
  }
 
  // Set memory usage after loop
  $m->setMemoryUsage('After Loop');
 
  // Unset array
  unset($a);
 
  // Set memory usage after unset
  $m->setMemoryUsage('After Unset');
 
  // Set end
  $m->setEnd();
 
  // Print memory usage statistics
  $m->printMemoryUsageInformation();


?>
CHECK Output of PHP Memory class

Objects to Array php


Every PHP coders have come accross Arrays and stdClass Objects (belongs to PHP Predefined Classes). Sometimes it’s very useful convert Objects to Arrays and Arrays to Objects. This is easy if arrays and objects are one-dimensional, but might be little tricky if using multidimensional arrays and objects.



This post defines two simple function to convert
:multidimensional Objects to Arrays
:multidimensional Arrays to Objects


Function to Convert stdClass Objects to Multidimensional Arrays
Objects to Array php


<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

 
 function objectToArray($d) {
  if (is_object($d)) {
   // Gets the properties of the given object
   // with get_object_vars function
   $d = get_object_vars($d);
  }
 
  if (is_array($d)) {
   /*
   * Return array converted to object
   * Using __FUNCTION__ (Magic constant)
   * for recursive call
   */
   return array_map(__FUNCTION__, $d);
  }
  else {
   // Return array
   return $d;
  }
 }
 
?>




Function to Convert Multidimensional Arrays to stdClass Objects
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

 
 function arrayToObject($d) {
  if (is_array($d)) {
   /*
   * Return array converted to object
   * Using __FUNCTION__ (Magic constant)
   * for recursive call
   */
   return (object) array_map(__FUNCTION__, $d);
  }
  else {
   // Return object
   return $d;
  }
 }

?>

Function usage

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


// Create new stdClass Object
 $init = new stdClass;
 
 // Add some test data
 $init->foo = "Test data";
 $init->bar = new stdClass;
 $init->bar->baaz = "Testing";
 $init->bar->fooz = new stdClass;
 $init->bar->fooz->baz = "Testing again";
 $init->foox = "Just test";
 
 // Convert array to object and then object back to array
 $array = objectToArray($init);
 $object = arrayToObject($array);
 
 // Print objects and array
 print_r($init);
 echo "\n";
 print_r($array);
 echo "\n";
 print_r($object);

?>

 

© 2014 4everTutorials. All rights resevered.

Back To Top