Related
Lets say for $numArr = array(10,20,30,40,50,60,70,80,90,100);
how to sum between specific range like 30 - 60 to get sum of 180.. (30+40+50+60).
edit : This is my latest code
<?php
function sum_array ($no1, $no2){
$array = array(10,20,30,40,50,60,70,80,90,100);
$input = array_slice($array, $no1, $no2);
return array_sum($input);
}
echo sum_array(0,3);
?>
I made a basic function for this according to u guys replies .. though still i want to put some validations into this like the parameters should be positive else the function should return -1 .. and what if the second index of the range is not in array.. like (90-120). Would it able to still sum what's in range and in array .. and give 190 to the above range.
$numArr = [ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 ];
$startValue = 30;
$endValue = 60;
$startIndex = array_search($startValue, $numArr);
$endIndex = array_search($endValue, $numArr);
$length = $endIndex - $startIndex + 1;
$result = array_sum(array_slice($numArr, $startIndex, $length));
print_r($result);
How I could generate a list of numbers (18 numbers), which are in a range which starts with 1 and ends with 36 (including 1 and 36), and the generated numbers must be different from numbers which exist in an array.
Example:
Array numbers: 27, 31, 18, 4, 15, 6
I need to output 18 random numbers which aren't in above array, and the numbers must not be duplicated.
Output I should get: 17, 21, 14, 28, 7, 8, 12, 20, 3, 5, 16, 2, 36, 11, 26, 13, 24, 35
function randomGen($min, $max, $quantity) {
$exluding_array = [1,2,3,4,5,6,7,8,9,10];
$numbers = range($min, $max);
shuffle($numbers);
if(range($min, $max) === $exluding_array) {
return "no";
} else {
return array_slice($numbers, 0, $quantity);
}
}
With this code I get random numbers without duplicates, but the returned numbers can be numbers from exluding_array.
You can use array_diff to remove all numbers of excluding_array from the generated numbers before slicing:
function randomGen($min, $max, $quantity) {
$excluding_array = [1,2,3,4,5,6,7,8,9,10];
$numbers = range($min, $max);
// Remove unwanted numbers
$numbers = array_diff($numbers, $excluding_array);
shuffle($numbers);
if (count($numbers) < $quantity) {
return "no";
} else {
return array_slice($numbers, 0, $quantity);
}
}
Note: I also improved your sanity check a bit, although returning "no" doesn't seem to be the best solution in that case. You might want to throw an exception as shown by vivek_23.
(Sample on PHP sandbox)
Another approach is you can array_flip the $excluding array and check for these numbers existence in $numbers. If we find them, we skip them, else we include it in our final array.
We could also throw an Exception if we can't produce as many numbers as $quantity.
<?php
function randomGen($min, $max, $quantity) {
$exluding_array = [1,2,3,4,5,6,7,8,9,10];
$exluding_array = array_flip($exluding_array);
$numbers = range($min, $max);
shuffle($numbers);
$filtered_numbers = [];
foreach($numbers as $curr_number){
if(isset($exluding_array[$curr_number])) continue;
$filtered_numbers[] = $curr_number;
}
if(count($filtered_numbers) < $quantity) throw new Exception("Can't generate numbers with the given quantity and range.");
return array_slice($filtered_numbers, 0, $quantity);
}
print_r(randomGen(1,36,10));
Demo: https://3v4l.org/mUi8A
You can also make the callee of this function implement a try-catch block to handle the exception gracefully.
I would make use of array_filter to filter out the excluded numbers:
function randomGen(int $min, int $max, int $quantity, array $excluded = []): array
{
$result = array_filter(range($min, $max), static function ($val) use ($excluded) {
return !in_array($val, $excluded, true);
});
shuffle($result);
return array_slice($result, 0, $quantity);
}
$result = randomGen(1, 36, 10, range(1, 10));
Demo: https://3v4l.org/nkbTK
End goal: Changing chunks of numbers in a database like 0000000 and 22222 and 333333333333 into different lengths. For example, phone numbers that may include prefixes like country codes (e.g. +00 (000) 000-0000, or a pattern of 2, 3, 3, 4), so the option of being able to change the length depending on a different phone number format would be nice.
I love the idea of using explode or chunk_split for the simplicity, as I will be processing a lot of data and I don't want it to drain the server too much:
$string = "1111111111";
$new_nums = chunk_split($string, 3, " ");
echo $new_nums;
^ Only problem here is that I can only use one digit for the length.
What's the best way to go about it? Should I create a function?
Although you mention a phone number in your example it sounds like you wanted something that could do more while also being allowed to specify multiple and variable chunk lengths. One way to do this is to create a function that takes your data, delimiter/separator character and a number of chunk values.
You could make use of func_num_args() and func_get_args() to figure out your chunk lengths.
Here is an example of such a function:
<?php
function chunkData($data, $separator)
{
$rebuilt = "";
$num = func_num_args();
$args = func_get_args();
if($num > 2)
{
for($i = 2; $i < $num; $i++)
{
if(strlen($data) > 0)
{
$string = substr($data, 0, $args[$i]);
$segment = strpos($data, $string);
if($segment !== false)
{
$rebuilt .= $string . $separator;
$data = substr_replace($data, "", 0, $args[$i]);
}
}
}
}
$rebuilt .= $data;
$rebuilt = rtrim($rebuilt, $separator);
return $rebuilt;
}
//Usage examples:
printf("Phone number: %s \n", chunkData("2835552093", "-", 3, 3, 4));
printf("Groups of three letters: %s \n", chunkData("ABCDEFGHI", " ", 3, 3, 3));
printf("King Roland's passcode: %s \n", chunkData("12345", ",", 1, 1, 1, 1, 1));
printf("Append leftovers: %s \n", chunkData("BlahBlahBlahJustPlainBlah", " ", 4, 4, 4));
printf("Doesn't do much: %s \n", chunkData("huh?", "-"));
?>
//Output:
Phone number: 283-555-2093
Groups of three letters: ABC DEF GHI
King Roland's passcode: 1,2,3,4,5
Append leftovers: Blah Blah Blah JustPlainBlah
Doesn't do much: huh?
With regex?
$regex = "/(\\d{2})(\\d{3})(\\d{3})(\\d{4})/";
$number = "111111111111";
$replacement = "+$1 ($2) $3-$4";
$result = preg_replace($regex, $replacement, $number);
https://regex101.com/r/gS1uC1/1
Problem:
I have a field in my MySQL table with the following value:
9, 10, 11, 12, 13, 14, 15, 16, 26, 27, 28, 29, 30, 31, 32
I use PHP to put the value of this field in the variable: $row['Exclude'];
The problem is that I am using a function called rand_except() that looks as following:
function rand_except($min, $max, $except)
{
//first sort array values
sort($except, SORT_NUMERIC);
//calculate average gap between except-values
$except_count = count($except);
$avg_gap = ($max - $min + 1 - $except_count) / ($except_count + 1);
if ($avg_gap <= 0)
return false;
//now add min and max to $except, so all gaps between $except-values can be calculated
array_unshift($except, $min - 1);
array_push($except, $max + 1);
$except_count += 2;
//iterate through all values of except. If gap between 2 values is higher than average gap,
// create random in this gap
for ($i = 1; $i < $except_count; $i++)
if ($except[$i] - $except[$i - 1] - 1 >= $avg_gap)
return mt_rand($except[$i - 1] + 1, $except[$i] - 1);
return false;
}
In order for this to work it needs to be like this:
$exclude = array(9, 10, 11, 12, 13, 14, 15, 16, 26, 27, 28, 29, 30, 31, 32);
$_SESSION['experimentversion'] = rand_except(1, 32, $exclude);
Question:
How can I take the database field $row['Exclude'] and transform it into an array so it will work with the function?
Simple. Use Explode function.
$s = "1,2,3,4";
$y = explode(",", $s);
print_r($y)
There is a explode method in php you can use this method
$string = '1,2,3,4,5';
$array = explode(",",$string);
print_r($array);
it will create an array.
$exclude = explode(', ', $row['Exclude']);
$str = '1,2,3,4,5';
$arr = explode(",",$str);
print_r($arr);
This should do the trick:
$exclude = explode(", ", $row['Exclude']);
use explode function.. for more info of Explode Visi this link
$row = "retrive your value from db";
$data = explode(", ",$row);
print_r($data); //here you will get array of your db field
I have this array:
$numbers = array(1, 2, 3);
I can grab a random value from it like so:
$numbers[array_rand($numbers)];
But I need to come up with different random variations of these values. For example
1
13
123
3
32
12
3
12
13
231
etc...
As you can see a number can't repeat more than once in each set, so we can't have sets like:
113
232
33
etc...
How can this be done?
This solution lets you handle with any size of array...same operation..
<?php
$numbers = array(1, 2, 3);
$count=count($numbers);
$result="";
$iterations=rand(1,$count);
for($i=0;$i<$iterations;$i++)
{
$selected=$numbers[array_rand($numbers)];
$numbers=remove_item_by_value($numbers,$selected);
$result=$result.$selected;
}
function remove_item_by_value($array, $val) {
foreach($array as $key => $value) {
if ($value == $val)
unset($array[$key]);
}
return $array;
}
echo $result;
?>
Now it will return you even random sized string:).
Define the array, get a random length, shuffle the array, slice the array:
$numbers = array(1, 2, 3);
$length = rand(1, count($numbers));
shuffle($numbers);
$result = array_slice($numbers, -$length);
Demo
One possible solution is:
$number1 = array(1, 2, 3);
$number2 = array(1, 2, 3);
$number3 = array(1, 2, 3);
$loop = 10;
for($i=0;$i<$loop;$i++) {
$bool1 = mt_rand(0, 1);
$bool2 = mt_rand(0, 1);
$randomNumber = $number1[array_rand($number1)];
if($bool1)
$randomNumber .= $number2[array_rand($number2)];
if($bool2)
$randomNumber .= $number3[array_rand($number3)];
echo $randomNumber;
}
This both randomly decides to choose between 1-3 digits and can use the numbers 1-3 as many times as possible. Just change $loop to the amount of times you want to run the generator.
I also just realised you could simplify this further:
$numbers = array(1, 1, 1, 2, 2, 2, 3, 3, 3);
$limit = mt_rand(1, 3);
$keys = array_rand($numbers, $limit);
$number = "";
if($limit == 1)
$number .= $numbers[$keys];
else {
foreach ($keys as $value) {
$number .= $numbers[$value];
}
}
Insert each number the maximum amount of times into the array you want it to appear in any number (maximum number of digits you want to generate). And randomly generate a number between 1-3 with mt_rand() to use as your array_rand() limit.
Well, define "random" (what are the chances of getting a 1-digit long string, or a 2-digit long, or a 3-digit long?), but here's one method:
$len = rand( 1, count( $numbers ) );
$result = '';
shuffle( $numbers );
for( $i = 0; $i < $len; ++$i ) {
$result .= $numbers[ $i ];
}
Note that this changes the original array. Make a copy of it if it shouldn't be changed.