﻿ PHP Math Exercise: Get the information regarding memory usage in KB or MB - w3resource

# PHP Math Exercises: Get the information regarding memory usage in KB or MB

## PHP math: Exercise-6 with Solution

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

Visual Presentation:

Sample Solution:

PHP Code:

``````<?php
\$memory_size = memory_get_usage(); // Get the memory usage of the script and store it in \$memory_size
\$memory_unit = array('Bytes','KB','MB','GB','TB','PB'); // Define an array containing memory size units

// 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]."\n";
?>
```
```

Output:

```Used Memory : 342.57 KB
```

Explanation:

In the exercise above,

• \$memory_size = memory_get_usage();: This line retrieves the current memory usage of the PHP script and stores it in the variable '\$memory_size'.
• \$memory_unit = array('Bytes','KB','MB','GB','TB','PB');: This line initializes an array '\$memory_unit' with memory size units ('Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'). These units will represent the memory size in a human-readable format.
• echo 'Used Memory : '.round(\$memory_size/pow(1024,(\$x=floor(log(\$memory_size,1024)))),2).' '.\$memory_unit[\$x]."\n";: This line calculates the memory size in the appropriate unit (KB, MB, etc.) and prints it along with the corresponding unit. It uses logarithmic calculations to determine the appropriate unit based on the size of '\$memory_size'. Finally, it appends a newline character ("\n") to the output.

Flowchart :

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿