PHP Serve 25 numbers in random order - php

I would like to serve an array of 25 elements randomly.
I'm not sure how to do this.
Say the array has numbers from 0 to 24.
I want to produce something like that:
5,4,6,7,8,9,10,20,21,22,23,24,25,1,2,11,14,15... etc
So if the generator outputs 23 it should not output it again
Thanks

$numbers = range(0, 24);
shuffle($numbers);
print_r($numbers);

Do you mean something like
$array;
$shuffledArray = shuffle($array);
In your concrete example you are talking about to output a comma separated string of numbers from 0 to 24
echo implode(',', shuffle(range(0,24));

for($i = 0; $i < 25; ++$i) {
$array[] = $i;
}
shuffle($array);
print_r($array);
The shuffle function is very useful in these cases.

<?php
$numbers = range(0, 24);
shuffle($numbers);
foreach ($numbers as $number) {
echo "$number ";
}
?>
http://php.net/manual/en/function.shuffle.php

$r = range(1,25);
shuffle($r);
var_dump($r);

If you have the array already, you can use the PHP function called shuffle():
http://php.net/manual/en/function.shuffle.php
if not, build the array like this:
<?php
$max = 24;
$num_array = array();
for($i=0;$i<=$max;$i++) $num_array[] = $i;
shuffle($num_array);
?>
Update: I've never seen the range function used before (by KingCrunch). Much better to use that one!

Related

Handle number in string php (Part2)

this is my problem 1 here: Handle number in string PHP . I solved it.
Now, i see new problem, you can see the picture:
I want to get only number, not date (500000 and 200000) and sum it.
This is my code without date:
$total= 0;
$ex = explode(' ',$_POST['txtSalary']);
function total($ex) {
global $total;
return $total+=$ex;
}
array_map('total',$ex);
echo $total."<br/>";
I try so much but no result, hope you can help me. Thank you!
I assume that your $_POST['txtSalary'] look like below:-
$_POST['txtSalary'] = '-27/07/2016: 5000000
-01/08/2016: 2000000';
So do like below:-
<?php
$_POST['txtSalary'] = '-27/07/2016: 5000000
-01/08/2016: 2000000';
$array = explode(PHP_EOL, $_POST['txtSalary']);
print_r($array);
$sum = 0;
foreach($array as $arr){
$sum += explode(': ',$arr)[1];
}
echo $sum;
Output:- https://eval.in/612692

create array using loop and input arithmetic progression value using loop

I'm noob in PHP programming and for my surprise I found it difficult to create an array using loop and to input in it values using arithmetic progression with +4 difference.I spent over an hour and tried a lot of code,searched so many examples.Below is my code that work(maybe) but not properly.
<?php
$array = [];
for($x=0;$x<10;$x++){
for($i=0;$i<100;$i+=4){
$array[] = $i;
}
break;
}
var_dump($array);
?>
I must have no more than 10(0-9 key) values,but because of $i the loop continues to 96 up to 24 keys.Maybe it's stupid question but I've totally blocked.
Is that what you want ?
<?php
$array = [];
for($x=0;$x<10;$x++){
$array[] = $x*4;
}
var_dump($array);
?>
Or maybe simpler
$array = range(0,36,4);
Doc for range : http://php.net/manual/fr/function.range.php
Then perhaps you have been overthinking this. You just need one loop, and can simply scale your key by 4:
foreach (range(0, 10) as $x) {
$array[] = 4 * $x;
}
Which will just add 0 for key 0, and 4 for key 1, and so on.
Note that for larger ranges, you should keep the classic for of course. It's more readable/obvious for math thingys anyway.
Use this:-
for ($x = 0; $x < 10; $x++) {
$array[$x] = $x * 4;
}
echo '<pre>';
print_r($array);
I think you must read basic of array here is a link that is useful for you link

How to reverse an array in php WITHOUT using the array reverse method

I want to know how to reverse an array without using the array_reverse method. I have an array called reverse array which is the one i want to reverse. My code is below. could someone point out what i am doing wrong as I cannot find any example of reversing an array this way anywhere else. my code is below.
<?php
//Task 21 reverse array
$reverseArray = array(1, 2, 3, 4);
$tmpArray = array();
$arraySize = sizeof($reverseArray);
for($i<arraySize; $i=0; $i--){
echo $reverseArray($i);
}
?>
<?php
$array = array(1, 2, 3, 4);
$size = sizeof($array);
for($i=$size-1; $i>=0; $i--){
echo $array[$i];
}
?>
Below is the code to reverse an array, The goal here is to provide with an optimal solution. Compared to the approved solution above, my solution only iterates for half a length times. though it is O(n) times. It can make a solution little faster when dealing with huge arrays.
<?php
$ar = [34, 54, 92, 453];
$len=count($ar);
for($i=0;$i<$len/2;$i++){
$temp = $ar[$i];
$ar[$i] = $ar[$len-$i-1];
$ar[$len-$i-1] = $temp;
}
print_r($ar)
?>
The problem with your method is when you reach 0, it runs once more and index gets the value of -1.
$reverseArray = array(1, 2, 3, 4);
$arraySize = sizeof($reverseArray);
for($i=$arraySize-1; $i>=0; $i--){
echo $reverseArray[$i];
}
Here's another way in which I borrow the code from here and update it so that I eliminate having to use a $temp variable and instead take advantage of array destructuring, as follows:
<?php
/* Function to reverse
$arr from start to end*/
function reverseArray(&$arr, $start,
$end)
{
while ($start < $end)
{
[$arr[$start],$arr[$end]] = [$arr[$end],$arr[$start]];
$start++;
$end--;
}
}
$a = [1,2,3,4];
reverseArray($a,0,count($a)-1);
print_r($a);
See live code
One of the advantages of this technique is that the array $a is reversed in place so there is no necessity of creating a new array.
The following improves the code so that one need not pass more than one parameter to reverseArray(); as well as indicating that there is no return value:
/* Function to reverse
$arr from start to end*/
function reverseArray(&$arr, $start=0): void
{
$end = count($arr)-1;
while ($start < $end)
{
[$arr[$start],$arr[$end]] = [$arr[$end],$arr[$start]];
$start++;
$end--;
}
}
$a = [1,2,3,4];
reverseArray($a);
print_r($a);
See here
Note: this revision works in PHP 7.2-7.4.2
how to reverse a array without using any predefined functions in php..
i had a solution for this problem...
here is my solution........
<?php
// normal array --------
$myarray = [1,2,3,4,5,6,7,8,9];
//----------------
$arr = [];
for($i=9; $i > -1; $i--){
if(!$i==0){
$arr[]= $i;
}
}
print_r($arr);
//the out put is [9,8,7,6,5,4,3,2,1];
?>

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";

Leading zeroes in PHP

I would like to present a list from 0 to 59 with the numbers 0 to 9 having a leading zero. This is my code, but it doesn't work so far. What is the solution?
for ($i=0; $i<60; $i++){
if ($i< 10){
sprintf("%0d",$i);
}
array_push($this->minutes, $i);
}
Using %02d is much shorter and will pad the string only when necessary:
for($i=0; $i<60; $i++){
array_push($this->minutes,sprintf("%02d",$i));
}
You are not assigning the result of sprintf to any variable.
Try
$padded = sprintf("%0d", $i);
array_push($this->minutes, $padded);
Note that sprintf does not do anything to $i. It just generates a string using $i but does not modify it.
EDIT: also, if you use %02d you do not need the if
Try this...
for ($i = 0; $i < 60; $i++) {
if ($i < 10) {
array_push($this->minutes, sprintf("%0d", $i));
}
array_push($this->minutes, $i);
}
You are ignoring the returned value of sprintf, instead of pushing it into your array...
important: The method you are using will result in some items in your array being strings, and some being integers. This might not matter, but might bite you on the arse if you are not expecting it...
Use str_pad:
for($i=0; $i<60; $i++){
str_pad($i, 2, "0", STR_PAD_LEFT)
}
I like the offered solutions, but I wanted to do it without deliberate for/foreach loops. So, here are three solutions (subtle variations):
Using array_map() with a designed callback function
$array = array_map(custom_sprintf, range(0,59));
//print_r($array);
function custom_sprintf($s) {
return sprintf("%02d", $s);
}
Using array_walk() with an inline create_function() call
$array = range(0,59);
array_walk($array, create_function('&$v', '$v = sprintf("%02d", $v);'));
// print_r($array);
Using array_map() and create_function() for a little code golf magic
$array = array_map(create_function('&$v', 'return sprintf("%02d", $v);'), range(0,59));

Categories