PHP Rounding up to specific set of numbers [duplicate] - php

This question already has answers here:
Find number which is greater than or equal to N in an array
(11 answers)
Closed 8 years ago.
I want to round up any given number to the nearest set of specific values only. The values are 5,10,20,25,50,100
So if the given number is 2 it will be rounding up to 5. If it's 71.6 it will be rounding down to 50, if it's 250 it will be rounding down to 100
Anybody can give me a clue how to do that?
Thanks a lot!

use a loop:
$numbers = array(5, 10, 20, 25, 50, 100);
$result = $input;
foreach ($numbers as $n) {
if ($input < $n) {
$result = $n;
break;
}
}

I found the answer here : Find number which is greater than or equal to N in an array. Thanks to #kAlmAcetA
function closest($array, $number) {
sort($array);
foreach ($array as $a) {
if ($a >= $number) return $a;
}
return end($array) // or return NULL;
}

Related

Performing arithmetic operations on arrays [duplicate]

This question already has answers here:
PHP FizzBuzz Logic
(3 answers)
Another FizzBuzz solution [closed]
(3 answers)
PHP Fizzbuzz Challenge [closed]
(3 answers)
PHP loop increment quirk - (FizzBuzz in one line)
(4 answers)
Closed 2 months ago.
I came across this php interview question while researching pre-interview test questions.
Given an array of integers, compute a total score based on the following rules:
Add 1 point for every even number in the array
Add 3 points for every odd number in the array
Add 5 points for every time you encounter an 8 in the array
Examples:
Input: my_numbers = [1, 2, 3, 4, 5]
Output: 11
Input: my_numbers=[15, 25, 35]
Output: 9
Input: my_numbers=[8, 8]
Output: 10
How to approach this particular task?
my attempt
<?php function find_total( $my_numbers ) {
//Insert your code here \
$total = 0;
foreach($my_numbers as $val) {
if ($val % 2 == 0) {
echo (++$val);
} else
echo ($val += 3);
}
if ($val == 8) {
echo($val += 5);}
}
?>
I am not sure your sample answers are correct (8 is an even number and should attract 1 for that as well as the 5), but to give the answer you asked for use this (PHP):
(EDITED in response to mickmackusa's and Robin Bastiaan's comments)
$total = 0;
foreach($myarray as $value) {
if ($value === 8) {
$total += 5;
} elseif (!($value % 2)) {
++$total;
} else
$total += 3;
}

Round to Highest Factor with Variable Scale? [duplicate]

This question already has answers here:
Round to max thousand, hundred etc in PHP
(5 answers)
Closed 5 years ago.
PHP's floor() and ceil() is useful for rounding floats to their nearest integers.
But what if we need to find the highest multiple of 10 (hundreds, thousands, etc.) for a given number? For example:
num_to_scale(538.9) // 500
num_to_scale(543123654.01234) // 5000000
Try this code, check the live demo. You also can refer to this post.
$floor = floor($v);
return str_pad(substr($floor, 0, 1), strlen($floor), '0');
function num_to_scale($number) {
$multiple=1; $test=1;
for ($i=1; $test>=1; $i++) {
$factor = $multiple/10;
$test = $number/$multiple;
$multiple = $multiple*10;
$scale = floor($number/$factor)*$factor;
} return $scale;
}
or more simply:
function num_to_scale($n) {
$m=1; $t=1;
for ($i=1; $t>=1; $i++) {
$f=$m/10; $t=$n/$m; $m=$m*10; $s=floor($n/$f)*$f;
} return $s;
}
Combined with a helper function to convert integers to text strings, we can easily do something like this:
echo 'Over '.num_to_scale(5395206).' units sold.';
// Over five million units sold.
try this:
function num_to_scale($number) {
$num = (int) floor($number);
$ln = strlen($num) - 1;
return (int) floor($num / pow(10, $ln)) * pow(10, $ln);
}
My answer uses logarithm :
function num_to_scale($var) {
$nbDigits = (int)log($var,10);
return (int)($var/10**$nbDigits)*10**$nbDigits;
}

How can i modify the php code to recieve 5 numbers without duplicates/repeating numbers?

i have this php code:
<?php
function GetRand($N, $min=1, $max=59) {
$Local = array();
mt_srand(time());
for ($i=0;$i<$N;$i++)
$LocalArr [] = mt_rand($min, $max);
return $LocalArr;
}
$A = GetRand(5);
foreach($A as $K=>$v) echo "$v ";
?>
The result is 5 numbers between 1 and 59. The problem is that sometimes i receive results like this:
43 9 13 9 7
In those 5 numbers, there is the number 9 twice. I would like to change the php code, so everytime when there is a number that repeats, this number should be skipped and instead of the repeated number should be represented another number, so that every time i have 5 numbers and no duplicates between them.
Thank you very much in Advance!
$numbers = range(1, 59);
shuffle($numbers);
var_dump(array_slice($numbers, 0, 5));
Try this (untested):
<?php
$randoms = array(rand(1,59));
while(sizeof($randoms) <= 5) {
$randoms[] = rand(1,59);
$randoms = array_unique($randoms);
}

how to get rand same array in php

what i want to do is something like memory game, but I keep cannot get the same number with the out put
$numbers = range(1, 15);
shuffle($numbers);
foreach($numbers as $key){
echo $numbers[array_rand($numbers)];
break;
}
now the out put will be something like this
4 2 3 3
1 5 3 6
2 3 4 5
10 9 8 10
but how to I do it as rand array and with same 2 array number, which is i can match the number.
what i want in out put is
2 3 1 4
3 4 2 1
5 6 9 7
7 9 6 5
so like this i can get the match in 2 same number
any idea how to do it?
thanks
Your question is a bit confusing and vague. I extrapolate that you want to shuffle and display an array of numbers, two of each, in random order. To do that:
<?php
$numbers = range(1, 5);
$numbers = array_merge($numbers, $numbers);
shuffle($numbers);
echo implode(' ', $numbers);
This outputs, for instance, 3 5 1 5 1 2 3 4 2 4.
The array_rand() call in the foreach in your code makes absolutely no sense. If the above isn't what you wanted, please revise your question to be clearer.
First you have to do an array with couple values
// Generate array with values from 1 to 8
$arNumbers = range(1, 8);
// Duplicate the array so get copy of each number
$arNumbers = array_merge($arNumbers, $arNumbers);
// Shuffle the array
shuffle($arNumbers);
// And now display them
foreach($arNumbers as $nNumber)
{
// Do some business
}
Hope it helps :)
Try this. It is a simple way.
$numbers=range(1, 15);
//Get 4 unique random keys from $numbers array.
$rand_keys = array_rand($numbers, 4);
//print out the random numbers using the
//random keys.
foreach ($rand_keys as $k=>$i) {
echo $numbers[$i]." ";
}
Hope this will helps you...
If I get you correctly, you can achieve what you want to do with the following:
// make sure these are even numbers
$rows = 4;
$cols = 4;
$set = range(1, ($rows * $cols) / 2);
$numbers = array_merge($set, $set);
shuffle($numbers);
foreach (array_chunk($numbers, $cols) as $row) {
foreach ($row as $col) {
printf('%-5d', $col);
}
echo "\n";
}
Outputs:
3 7 2 1
4 6 8 5
6 3 8 4
2 5 7 1
Do something like:
$numbers = range(1, 15);
shuffle($numbers);
$used_numbers = array();
foreach($numbers as $key){
$this_number = $numbers[array_rand($numbers)];
$used_numbers[] = $this_number;
echo $this_number;
break;
}
$_SESSION['numbers'] = $used_numbers;
Then you can use the $_SESSION to access the numbers on another page (after reload perhaps), or use the same $used_numbers array to access them.
If you try:
$numbers = range(1, 15);
shuffle($numbers);
$used_numbers = array();
foreach($numbers as $key){
$this_number = $numbers[array_rand($numbers)];
$used_numbers[] = $this_number;
echo $this_number;
break;
}
echo '<br />';
foreach($used_numbers AS $number) {
echo $number;
}
You will see it returns the same number.

perform round function without using round() in php [duplicate]

This question already has answers here:
Print numeric values to two decimal places
(6 answers)
Closed 11 months ago.
without use of round() function perfrom the round() in php
$a = "123.45785";
$v = round($a);
output: 123.46;
it had done by round function but i want to get output without use of round and number_format() function.
Here's a way of doing it with arithmetics:
function my_round($num, $places = 2) {
// Multiply to "move" decimals to the integer part
// (Save one extra digit for rounding)
$num *= pow(10, $places + 1);
// Truncate to remove decimal part
$num = (int) $num;
// Do rounding based on the last digit
$lastDigit = $num % 10;
if ($lastDigit >= 5)
$num += 10;
// Remove last digit
$num = (int) ($num/10);
// "Move" decimals in place, and you're done
$num /= pow(10, $places);
return $num;
}
You have sprintf.
$a = "123.45785";
echo sprintf("%01.2f", $a); // output: 123.46

Categories