w3resource logo


php exercises

PHP Math functions - Exercises, Practice, Solution

rating Average rating 8 out of 10. Total 2 users rated.

<<PreviousNext>>

PHP Math functions [ 6 exercises with solution]

1. Write a PHP script to find the maximum and minimum marks from the following set of arrays. Go to the editor
Sample arrays :
$marks1 = array(360,310,310,330,313,375,456,111,256);
$marks2 = array(350,340,356,330,321);
$marks3 = array(630,340,570,635,434,255,298);
Expected Output :
Maximum marks : 635
Minimum marks : 111

<?php
$marks1 = array(360,310,310,330,313,375,456,111,256); 
$marks2 = array(350,340,356,330,321); 
$marks3 = array(630,340,570,635,434,255,298); 
$max_marks = max(max($marks1),max($marks2),max($marks3)); 
$min_marks = min(min($marks1),min($marks2),min($marks3)); 
echo "Maximum marks : ".$max_marks.'<br>';
echo "Minimum marks : ".$min_marks;
?>

2. Write a PHP script which round the following values with 1 decimal digit precision. Go to the editor
Sample values and Output :
1.65 --> 1.7
1.65 --> 1.6
-1.54 --> -1.5

<?php
echo round( 1.65, 1, PHP_ROUND_HALF_UP).'<br>';   //  1.7
echo round( 1.65, 1, PHP_ROUND_HALF_DOWN).'<br>'; //  1.6
echo round(-1.54, 1, PHP_ROUND_HALF_EVEN).'<br>'; // -1.5
?>

3. Write a PHP script to generate random 11 characters string of letters and numbers. Go to the editor

<?php
$x = rand(10e12, 10e16);
echo base_convert($x, 10, 36);
?>

4. Write a PHP script to convert scientific notation to a int and a float. Go to the editor
Sample scientific notation : 4.5e3
Expected Output : 4 & 4500

<?php
$val = '4.5e3';
$ival = (int) $val;
$fval = (float) $val;
echo $ival.'<br>';
echo $fval;
?>

5. Write a PHP script to extract mantissa and exponent from a floating point value. Go to the editor
Sample floating value : 0.0456
Expected Output :
Exponent part : -4
Mantissa part : 0.7296

<?php
$float_num = 0.0456;
$exponent_part = ( floor(log($float_num, 2)) + 1 );
$mantissa_part = ( $float_num * pow(2, -$exponent_part) );
echo 'Floating value : '.$float_num.'<br>';
echo 'Exponent part  : '.$exponent_part.'<br>';
echo 'Mantissa part  : '.$mantissa_part.'<br>';
?>

6. Write a PHP script to get the information regarding memory usage in KB or MB etc. Go to the editor

<?php
$memory_size = memory_get_usage();
$memory_unit = array('Bytes','KB','MB','GB','TB','PB');
// Display memory size into kb, mb etc.
echo 'Used Memory : '.round($memory_size/pow(1024,($x=floor(log($memory_size,1024)))),2).' '.$memory_unit[$x];
?>

Go Top

Write your code here :

Go Top

More to Come !



<<PreviousNext>>