Monthly Archives: Mar 2018

PHP – Round a value up to the nearest multiple value

php-banner

round(), ceil() and the like to a good job of most things in PHP.

But what if you need to round the number up to the nearest 10 or nearest 15 etc.  This little function makes this easy:

function roundToNearestMultiple($value, $roundTo)
{
    $mod = $value%$roundTo;
    return $value+($mod<($roundTo/2)?-$mod:$roundTo-$mod);
}

Usage:

$number= roundToNearestMultiple($input, 10);

/* 
    Outputs:
      $input= 7 -> $number= 10
      $input= 85 -> $number= 90
*/

$number= roundToNearestMultiple($input, 15);

/* 
    Outputs:
      $input= 89 -> $number= 90
      $input= 1869 -> $number= 1875
*/

 

Share this post:
read more

Create a random string with PHP

php-banner

How to create a random string with PHP.

Step 1:

Include the following function somewhere.

function randomstring($length)
{
  $string = "";
  $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  for($i=0;$i<$length;$i++)
  $string.=substr($chars,rand(0,strlen($chars)),1);
  return $string;
}

I’ve only included upper and lower case characters here, but you can add anything to the $chars variable, and they will be included and picked at random.

Usage:

Just send the length of the string you want to return to the function when you call it, and it will return your random string.  So a random 15 character string would be:

$randomString= randomstring(15);

 

Share this post:
read more