How to improve array_rand() function with PHP? - php

I use the array_rand PHP function with an array. I use it with a data fixture function wich load a set of data in a loop like this:
$random_values = array();
for ($i = 0; $i < 20; $i++) {
$random_values[] = array_rand(["1","2","3","4","5"]);
}
My result is quite always "1" in the $random_values array, the native
PHP function seems not really random, Is there another stuff to do to
improve the randomization of my algorithm ?
Notice I already know there is an official documentation here, http://php.net/manual/fr/function.array-rand.php.

How's it going? So, with array_rand, it actually returns a random key within an array. Your current code does not put the random key value into the array you want to randomize. ie echo $random_value[$random_key]... See example below, hope this helps
$random_values = array("1","2","3","4","5");
for ($i = 0; $i < 20; $i++) {
$key = array_rand($random_values);
echo $random_values[$key] . "\n";
}

Related

Foreach over an array

I'd like ask on my problem with formatting array. I'm importing data to system from .XLSX. Function return me array which one looks like:
Array Index
My question is how I can insert this data to table if I know array with index 1 and with number 1 is Name e.t.c?
I can write SQL but I can't write foreach. I already tried make some foreach but without success.
Thank you one more time
Here is solution:
/** #var int $count */
$count = count($spreadsheet);
$s = array();
for($i = 1; $i < $count; ++$i) {
$s = $spreadsheet[$i];
}
return $s;

Using an index twice in PHP

I am trying to use a for loop where it looks through an array and tries to make sure the same element is not used twice. For example, if $r or the random variable is assigned the number "3", my final array list will find the value associated with wordList[3] and add it. When the loop runs again, I don't want $r to use 3 again. Example output: 122234, where I would want something along the lines of 132456. Thanks in advance for the help.
for($i = 0; $i < $numWords; $i++){
$r = rand(0, $numWords);
$arrayTrack[$i] == $r;
$wordList[$r] = $finalArray[$i];
for($j = 0; $j <= $i; $j++){
if($arrayTrack[$j] == $r){
# Not sure what to do here. If $r is 9 once, I do not want it to be 9 again.
# I wrote this so that $r will never repeat itself
break;
}
}
Edited for clarity.
Pretty sure you are over complicating things. Try this, using array_rand():
$final_array = array();
$rand_keys = array_rand($wordList, $numWords);
foreach ($rand_keys as $key) {
$final_array[] = $wordList[$key];
}
If $numWords is 9, this will give you 9 random, unique elements from $wordList.
See demo
$range = range(0, $numWords - 1); // may be without -1, it depends..
shuffle($range);
for($i = 0; $i < $numWords; $i++) {
$r = array_pop($range);
$wordList[$r] = $finalArray[$i];
}
I do not know why you want it.. may be it is easier to shuffle($finalArray);??
So ideally "abcdefghi" in some random order.
$letters = str_split('abcdefghi');
shuffle($letters);
var_dump($letters);
ps: if you have hardcoded array $wordList and you want to take first $n elements of it and shuffle then (if this is not an associative array and you do not care about the keys)
$newArray = array_slice($wordList, 0, $n);
shuffle($newArray);
var_dump($newArray);
You can try array_rand and unset
For example:
$array = array('one','two','free','four','five');
$count = count($array);
for($i=0;$i<$count;$i++)
{
$b = array_rand($array);
echo $array[$b].'<br />';
unset($array[$b]);
}
after you have brought the data in the array, you purify and simultaneously removing the memory array
Ok... I have NO idea why you are trying to use so many variables with this.
I certainly, have no clue what you were using $arrayTrack for.
There is a very good chance I am mis-understanding all of this though.
<?php
$numWords=10;
$wordList=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
$finalArray=array();
for ($i=0; $i<$numWords; $i++) {
start:
$r=rand(0,$numWords);
$wordChoice=$wordList[$r];
foreach ($finalArray as $word) {
if ($word==$wordChoice) goto start;
}
$finalArray[]=$wordChoice;
}
echo "Result: ".implode(',',$finalArray)."\n";

PHP - Help in FOR LOOP

I have an array and looping through it and pushing the data using for loop.
$test_data = [10,20,35,01,50,60,87,12,45,86,9,85];
Actually that's a sample data. But my data is a result similar to that which I get from PostgreSQL, a single column data.
Using the below function for $test_data.
for( $x=0; $x < 12; $x++ ) {
$chart_data['data1'] = $test_data[$x];
}
Result : {"data1":{"data": 85"}}
Here's the for loop which I use along the PostgreSQL result in the PHP.
for( $x=0; $x < pg_num_rows($query); $x++ ) {
$data['data1'] = pg_fetch_assoc($query);
}
Even here I get only the last row in the browser when I do - echo json_encode($data);
Something similar to the result what I've mentioned above.
First 9 rows are not getting inserted into the data[]. Only the last row is getting added to the array.
Please say me where I'm doing the mistake.
Thanks in advance.
Since arrays cannot have same key as index.
You need to rewrite it as ..
for( $x=0; $x < 12; $x++ ) {
$chart_data['data1'][] = $test_data[$x];
// ^^ <--- Add that.
}
As Loic suggested go with a foreach , I answered quickly so it didn't strike on my mind in the first place
foreach($test_data as $val)
{
$chart_data['data1'][] = $val;
}
You could do like this (without using pg_num_rows):
// better initialize the result array
$data = array('data1' => array());
while ($row = pg_fetch_assoc($query)) {
// here is the point, add element to the array
$data['data1'][] = $row;
}

How to change a foreach to a for loop?

I've read on a web page, explaining that in PHP it is must faster execution to do a for loop than a foreach. This is new to me, but I would like to test this for himself. How do I convert a foreach into a for loop in PHP? Using the one below as an example:
foreach ($station->ITEMS->ITEM as $trips=>$trip) {
$ny_trips[$trips] = $trip;
}
I've seen for loops in PHP, but not using 'as' in them. So I'm not sure how the above would look in PHP as a for loop. Would it also require doing a count() of $station->ITEMS->ITEM? Thanks!
Assuimg the keys on the array are a perfect numerical sequence starting at 0 then this is what you are looking for.
for($x = 0, $nItems = count($station->ITEMS->ITEM); $x<$nItems; $x++) {
$ny_trips[$x] = $station->ITEMS->ITEM[$x];
}
If the keys are non-numeric then or not in perfect order then you need to do something like this.
$keys = array_keys($station->ITEMS->ITEM);
for($x = 0, $nItems = count($station->ITEMS->ITEM);$x < $nItems; $x++) {
$ny_trips[$keys[$x]] = $station->ITEMS->ITEM[$keys[$x]];
}
for($i=0;$i < count($station->ITEMS->ITEM);$i++){
$ny_trips[$i] = $station->ITEMS->ITEM[$i];
}

alternatives to php in_array for large arrays for avoiding duplicates entries

I need to generate a large list of random numbers from 600k to 2000k, but the
list can not have duplicates.
My current 'implementation' looks like this:
<?php
header('Content-type: text/plain');
$startTime = microtime(true);
$used = array();
for ($i=0; $i < 600000; ) {
$random = mt_rand();
//if (!in_array($random, $used)) {
$used[] = $random;
$i++;
//}
}
$endTime = microtime(true);
$runningTime = $endTime - $startTime;
echo 'Running Time: ' . $runningTime;
//print_r($used);
?>
If I keep the in_array test commented the processing time is around 1 second, so
the mt_rand calls and the used array filling are relatively 'cheap' but when I uncomment
the in_array test bad things happens! (I'm just waiting -it's been more then 10 minutes- for the script to terminate...)
So I'm looking for alternatives either on the duplicate detection side or in the generation part (How could i generate random numbers without the risk of getting duplicates)
I'm open to any suggestion.
For a quick/dirty solution, does using/checking array keys improve your speed at all?
$used = array();
for ($i = 0; $i < 600000; ) {
$random = mt_rand();
if (!isset($used[$random])) {
$used[$random] = $random;
$i++;
}
}
$used = array_values($used);
in_array requires to search the whole array in the worst case, that means linear costs (O(n)). But using the array key as – well – the key, the costs are constant (O(1)) since the costs for array access is always constant.
You could for example do something like this instead
$random = mt_rand();
$array = range($random, $random + 600000);
$array = shuffle($array);
That would create a array that first is in order, but then it shuffles the array, so the values will be random. No collisions! :D
If you do the looping anyways and if you don't need more than 600000 why would you check them at all, why not just append $i to $random. done. not random enough?
for ($i = 0; $i < 600000; $i++)
{
$yourArray[] = mt_rand() . $i;
}
Furthermore there is the array function array_unique, which removes duplicate values from an array.

Categories