I have an array that contains both strings and numeric values, While using this code I keep getting the highest string value, how to get only numeric max values from the array?
$maxprice = max($textpieces);
I have also tried this but this just returns the number of keys in the array
$maxprice = max(array_search($textpieces));
thanks for your help! I have looked but the max function here does not give any information http://php.net/manual/en/function.max.php
I have also looked at this solution Find highest max() of mixed array but is it possible to get it without building an custom function?
$maxprice = max(array_filter($textpieces, 'is_numeric'));
It at first filters only entries that contains digits only (integers) and then extracts max() from it
The following solution:
$max = array_reduce($textpieces, function($max, $i) {
if (is_numeric($i) && $i > $max) {
return $i;
}
return $max;
});
var_dump($max);
could be a bit more performance (from both CPU and memory perspectives) but is more complicated as well.
Related
I'm searching for an algorithm to remove gaps between numbers. Example of my problem:
Here is a range of integers: [1,2,3,4,9,10,11,17...]
I need to make those numbers like this: [1,2,3,4,5,6,7,8...]
Can anyone provide me with a working example of PHP code to obtain such a result?
You should fetch min and max from an array and create the range,
$min = min($arr);
$max = max($arr);
print_r(range($min,$max));
You can make by using range function as:
// given array 2,4,6 and 9 are missing.
$arr1 = array(1,3,5,7,8,10);
// construct a new array using range function by giving min(given array) and max(given array) value
$arr2 = range(min($arr1),max($arr1));
I've a loop that generates an array of all possible combinations of binary bits by giving the number of bits, but I got a memory issue when the number of its exceeds 20.
So I'm looking for a way to remove or empty the previous array values for example if the array reaches 1k or 2k values, here's the code :
for ($i = 1; $i <= ($listN - 1); $i++) {
$reverseBits = array_reverse($bits);
$prefixBit = preg_filter('/^/', '0', $bits);
$prefixReverseBits = preg_filter('/^/', '1', $reverseBits);
$bits = array_merge($prefixBit, $prefixReverseBits);
unset($prefixBit, $prefixReverseBits, $reverseBits);
}
I've tried this one but it does not work, the array will be fully empty outside the loop :
if(count($bits) > 1000){
unset($bits);
$bits = array();
}
Thank you for your help
Your code simply does nothing, if the $bits array is empty, because array_reverse and preg_filter do not modify the array size and array_merge only adds the existing numers together. So en empty array will always stay empty.
Instead set your "emtpy" array to the 1 bit default array ['0','1']:
if(count($bits) > 1000){
$bits = array('0','1');
}
In case you want to keep your "last 1000" results instead of deleting all reasults you got so far think about using $bits = array_slice($bits, 0, 1000); at the beginning of your loop.
For achieving something like that, you simply have to do something of the sort:
if(count($bits) > 1000){
$bits = array_slice($bits, 1000);
}
This will slice the array from the offset 1000 and leave the rest of the items of the array, intact.
Reference: http://php.net/manual/en/function.array-slice.php
For example i have an array like this [-1,-1,-1,-1,-1,-1,2.5,-1,-1,8.3]
I want to count the element which are not -1 like except of the -1. Is there any function in php to get this ? One approach which i think is
Count the total array - count of the -1 in the array.
how can we achieve this.
P.S : please provide me a comment why this question deserve negative vote.
Like #MarkBaker said, PHP doesn't have a convenient function for every single problem, however, you could make one yourself like this:
$arr = [-1,-1,-1,-1,-1,-1,2.5,-1,-1,8.3];
function countExcludingValuesOfNegativeOne ($arr) {
return count($arr) - array_count_values(array_map('strval', $arr))['-1'];
}
echo countExcludingValuesOfNegativeOne($arr); // Outputs `2`.
It just counts the whole array, then subtracts the number of negative 1s in the array. Because PHP throws an error if any element in the array isn't a string 1 when using array_count_values, I've just converted all elements of the array to a string using array_map('strval', $arr) 2
you can use a for loop counter skipping for a specific number.
function skip_counter($array,$skip){
$counter = 0;
foreach ($array as $value) {
if ($value != $skip) $counter++;
}
return $counter;
}
then you call skip_counter($your_list, $number_to_be_skipped);
I'm trying to generate a unique randomized array with exceptions,
i got this far:
function rand_except($min, $max,$no_numbers, $except) {
//loop until you get a unique randomized array without except number
$end=false;
while (!$end){
$numbers = rand_array($min, $max,$no_numbers);//get unique randomized array
if(!in_array($except,$numbers)){
$end=true;
break;
}
}
return $numbers;
}
but now i want the function to loop until the except parameter isn't in the array
I suspect it would be easier to solve this problem by updating the rand_array function (or writing a modified version of it) to generate the array without the $except value to start with.
If that is not an option, here is one possible solution that doesn't involve calling the rand_array function over and over again:
$numbers = rand_array($min, $max-1, $no_numbers);
for ($i = 0; $i < count($numbers); $i++) {
if ($numbers[$i] >= $except) {
$numbers[$i] += 1;
}
}
You call the rand_array function but specify one less than the actual maximum number you want in the array. Then you loop over the results, and any value that is greater than or equal to the $except value, you increment by 1.
This is assuming that the $except value is in the range $max to $max. If not, you can just return rand_array($min, $max, $no_numbers); as is.
Does anyone know what's the randomness of PHP's shuffle() function? Does it depend on the operating system?
Does it use PHP's own seeder?
Is it possible to use mt_rand() as generator?
shuffle() function is based on the same generator as rand(), which is the system generator based on linear congruential algorithm. This is a fast generator, but with more or less randomness. Since PHP 4.2.0, the random generator is seeded automatically, but you can use srand() function to seed it if you want.
mtrand() is based on Mersenne Twister algorithm, which is one of the best pseudo-random algorithms available. To shuffle an array using that generator, you'd need to write you own shuffle function. You can look for example at Fisher-Yates algorithm. Writing you own shuffle function will yield to better randomness, but will be slower than the builtin shuffle function.
Update for PHP 7.1
Since the rng_fixes rfc was implemented for PHP 7.1, the implementation of shuffle now utilizes the Mersenne Twister PRNG (i.e. it uses mt_rand and is affected by calling mt_srand).
The legacy system PRNG (rand) is no longer available; the functions rand and srand are in fact aliased to their mt_ equivalents.
Based on Mirouf's answer (thank you so much for your contribution)... I refined it a little bit to take out redundant array counting. I also named the variables a little differently for my own understanding.
If you want to use this exactly like shuffle(), you could modify the parameter to be passed by reference, i.e. &$array, then make sure you change the return to simply: "return;" and assign the resulting random array back to $array as such:
$array = $randArr; (Before the return).
function mt_shuffle($array) {
$randArr = [];
$arrLength = count($array);
// while my array is not empty I select a random position
while (count($array)) {
//mt_rand returns a random number between two values
$randPos = mt_rand(0, --$arrLength);
$randArr[] = $array[$randPos];
/* If number of remaining elements in the array is the same as the
* random position, take out the item in that position,
* else use the negative offset.
* This will prevent array_splice removing the last item.
*/
array_splice($array, $randPos, ($randPos == $arrLength ? 1 : $randPos - $arrLength));
}
return $randArr;
}
It's random just like rand();
And as PHP style you don't need to seed
mt_rand()
Generates a random number.
shuffle()
Randomizes an array. It also generates new keys in the array rather than just rearranging the old ones.
If you want to seed in PHP you would have used mt_strand().
However, since PHP 4.2.0 seeding is done automatically in PHP when you call mt_rand.
Works with associative and numeric arrays:
function mt_shuffle_array($array) {
$shuffled_array = [];
$arr_length = count($array);
if($arr_length < 2) {
return $array;
}
while($arr_length) {
--$arr_length;
$rand_key = array_keys($array)[mt_rand(0, $arr_length)];
$shuffled_array[$rand_key] = $array[$rand_key];
unset($array[$rand_key]);
}
return $shuffled_array;
}
$array = [-2, -1, 'a' => '1', 'b' => '2', 'c' => '3', 11, 'd' => '4', 22];
$shuffled_array = mt_shuffle_array($array);
I've created a function who sort my array randomly.
/**
* Build a random array
*
* #param mixed $array
*
* #return array
*/
function random_array($array) {
$random_array = array();
// array start by index 0
$countArray = count($array) - 1;
// while my array is not empty I build a random value
while (count($array) != 0) {
//mt_rand return a random number between two value
$randomValue = mt_rand(0, $countArray);
$random_array[] = $array[$randomValue];
// If my count of my tab is 4 and mt_rand give me the last element,
// array_splice will not unset the last item
if(($randomValue + 1) == count($array)) {
array_splice($array, $randomValue, ($randomValue - $countArray + 1));
} else {
array_splice($array, $randomValue, ($randomValue - $countArray));
}
$countArray--;
}
return $random_array;
}
It's not the best way to do that but when I've used the function shuffle, it was always returning a random array in the same order. If this could help someone, I will be happy !