This question already has answers here:
Break long string into pieces php
(5 answers)
Closed 3 years ago.
I want to make a program which splits a long number into pieces of 13 digited number such that I can loop for every 13 digits just using php.
$number = 012345678901230123456789123
Should output
0123456789123
0123456789123
And it should be for any large number having the number of digit multiple of 13.It looks about looping and algorithm but I want to make it as short as possible and I have doubts on how to do it. So I am just asking about the main concept.
The most dynamic solution is probably to use array_functions on the string.
So str_split to make it array then chunk it in size 13 and implode the arrays.
$number = "012345678901230123456789123";
$arr = array_chunk(str_split($number), 13);
foreach($arr as &$val){
$val = implode($val);
}
https://3v4l.org/LsNFt
You can create a function where you can use your string and size as parameter and return an array of strings of the desired length:
function splitString($str, $packetSize) {
$output = [];
$size = strlen($str);
for ($i = 0; $i < $size; $i += $packetSize) {
if ($i + $packetSize < $size) {
$output[]= substr($str, $i, $packetSize);
} else {
$output[]=substr($str, $i);
}
}
return $output;
}
This question already has answers here:
Get the sum of all digits in a numeric string
(13 answers)
Closed 5 years ago.
I am getting o/p like "11111" and I want to sum all these digits that should become 5. But if I use count count it is showing one only i.e, 1.Rather it should show 5.
Below is my code,
$count = count($inventory['product_id']);
$product_total = $count;
echo $product_total;//o/p => 1.
I need echo $product_total;//o/p => 5.
You can use the following using str_split to get an array with all characters (in your case digits) and using array_sum to get the sum of all the digits:
$digits = "11112";
$arrDigits = str_split($digits);
echo array_sum($arrDigits); //6 (1 + 1 + 1 + 1 + 2)
Demo: https://ideone.com/tZwi9J
Count is used for counting array elements.
What you can do in PHP, is to iterate over a string using either a foreach (not 100% sure) or for loop for this and accessing the elements like array elements by their index:
$str = '111111123545';
$sum = 0;
for ($i = 0; $i < strlen($str); $i++) {
$sum += intval($str[$i]);
}
print $sum; // prints 26
Alternativly, you can split the string using no delimiter and using the array_sum() function on it:
$str = '111111123545';
$sum = array_sum(str_split($str));
print $sum; // prints 26
array_sum(str_split($number));
Another possible way to count the list of digits in PHP is:
// match only digits, returns counts
echo preg_match_all( "/[0-9]/", $str, $match );
// sum of digits
echo array_sum($match[0]);
Example:
$ php -r '$str="s12345abas"; echo "Count :".preg_match_all( "/[0-9]/", $str, $match ).PHP_EOL; echo "Sum :".array_sum($match[0]).PHP_EOL;'
Count :5
Sum :15
This question already has answers here:
PHP rand() exclude certain numbers
(10 answers)
Closed 6 years ago.
How would I generate a random number from a range of numbers between 1 and 10 while excluding an array of numbers e.g. 4,5,6.
$exclude = array(4,5,6);
The following code allows to generate random numbers within a range however only for a single number and not an array of numbers
function randnumber() {
do {
$numb = rand(1,10);
} while ($varr == 4);
return $numb;
}
Create a loop that iterates until a generated random number using rand function is not in array. If the generated number is found in array, again another random number is generated.
do {
$number = rand(1,10);
} while(in_array($number, array(4,5,6)));
echo $number;
or
while(in_array(($number = rand(1,10)), array(4,5,6)));
echo $number;
You can use it like a function too:
<?php
function randomNo($min,$max,$arr) {
while(in_array(($number = rand($min,$max)), $arr));
return $number;
}
echo randomNo(1,10,array(4,5,6));
The above function, does the same process, in addition, you can reuse the code. It gets minimum and maximum number and the array of values to exclude.
Finally,
without loop, but with recursive function. The function generates a random number and returns if it is not found in the exclude array:
function randomExclude($min, $max, $exclude = array()) {
$number = rand($min, $max);
return in_array($number, $exclude) ? randomExclude($min, $max, $exclude) : $number;
}
echo randomExclude(1,10,array(4,5,6));
<?php
$exclude = array(4,5,6); // The integers to excluded
do
{
$x = rand(1, 10); // Generate a random integer between 1 and 10
}while(in_array($x, $exclude)); // If we hit something to exclude, try again
echo $x; // A random integer not excluded
?>
It would be wise to check if not all inputs are excluded to avoid infinite loops
You can simply do this, using array functions like this:
function my_rand($min, $max, array $exclude = array())
{
$range = array_diff(range($min, $max), $exclude);
array_shuffle($range);
return array_shift($range);
}
Some time ago I also wanted to become rid of these nasty little while loops. Reduced to fit your version of the problem, my approach would be to:
first generate a random number which in range (10 - 3) to indicate the position of the number to be generated in the hypothetical list of numbers in the desired range excluding {4,5,6}
second increment this value by the lower range (1)
third increment by 1 for every number in the set {4,5,6} it is equal to or greather (in order from the smallest to the highest number in that set)
So, all in all I'd basically stretch and blurr the hypothetical set of numbers the generated random value can be to fit into the possible outcomes.
$total = range(0,10);
$exclude = range(4,6);
$include = array_diff($total, $exclude);
print_r (array_rand($include));
This question already has answers here:
Generating UNIQUE Random Numbers within a range
(14 answers)
Closed 7 years ago.
I am trying to find a solution in PHP that can generate three random numbers.
At the moment I have this that generates a random number that is different from $randNum;
The numbers need to be different from each other and also different from the variable $randNum
Thank you
$wrong = $randNum;
while ($wrong == $randNum) {
$wrong = rand(0,$max - 1);
}
<?php
$numbers = [];
for($i = 0; $i < 10; $i++){
$number = rand (1,15);
while (in_array($number, $numbers)){
$number = rand (1,15);
}
$numbers[] = $number;
}
echo '<pre>';
print_r($numbers);
echo '</pre>';
This function generates unique 10 random numbers, range from 1-15 you can easy change this script to your needs.
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