I have two values: #FFF & #000
I want to echo randomly anyone, for that I tried:
$color = array('#FFF','#000');
$color = array_rand($color);
$color = $color[$color];
echo $color;
But it doesn't display anything.
You must need to take care of 2 things,
One, if you overwrite the variable with same name then, it will not produce your desired result.
Second, array_rand() will generate the random key
Why your code is not working, because, your initial array is $color:
$color = array('#FFF','#000');
After this, you are using array_rand(), which will give random key
$color = array_rand($color);
Now, your $color is overwrite from array to integer value. it means when you try to access $color[$color] this will give you nothing because, its not defined or overwritten.
Solution: just change your variable name specially array. using proper variable name is a good approach and this will help to others who will work on your work after you.
Example:
<?php
$colorArray = array('#FFF','#000');
$colorKey = array_rand($colorArray);
$colorName = $colorArray[$colorKey];
echo $colorName;
?>
Capture random index in other variable let say $key.
$color = array('#FFF','#000');
$key = array_rand($color);
echo $color[$key];
Note: array_rand — Pick one or more random keys out of an array
Demo
You had a good idea using array_rand
array_rand — Pick one or more random keys out of an array
However you are overwriting your array. ($color)
Try that instead :
$arrayRand = array_rand($color);
$randomColor= $color[$arrayRand];
Related
Lets say I have an array looking like this:
$sql = array("name"=>"Peter", "active"=>1 , "age"=>30)
and a loop looking like this:
for($i=0;$i<count($sql);$i++){
$value[$i] = ($sql[$i]);
echo $value[$i];
}
I want the loop to iterate through the array and assign each value to a new variable.
In this code i tried to make it store the values in:
value1
value2
value3
But sadly this doesnt work, thus I am here seeking help.
Or is it a problem that i got an associative array instead of a numeric one?
I dont want to use this loop on this array only but on other arrays with different keys and length aswell.
Edit: I think I may have not wrote it cleary enough to tell you what i want to achieve:
I want to have three string values at the end of the loop not stored in an array:
Variable1 should contain "Peter"
Variable2 should contain "1"
Variable3 should contain "30"
Plus I want this loop to be dynamic, not only accepting this specific array but if I were to give it an array with 100 Values, I would want to have 100 different variables in which the values are stored.
Sorry for not being clear enough, I am still new at stackoverflow.
Going by your condition, assign each value to a new variable, I think what you want would be to use Variable variables. Here is an example:
<?php
$sql = array("name"=>"Peter", "active"=>1 , "age"=>30);
$count = 1;
foreach ($sql as $value) {
$x = 'value'.$count;
$$x = $value; //here's the usage of Variable variables
$count++;
}
echo $value1.'<br/>';
echo $value2.'<br/>';
echo $value3.'<br/>';
I went to your sample variables ($value1, $value2, etc.). I also changed your loop to foreach to easily loop the array. And I also added a $count that will serve as the number of the $value variable.
The $count wouldn't be necessary if your index are numeric, but since its an associative array, something like this is needed to differentiate the variables created
A brief explanation as requested:
$x contains the name of the variable you want to create (in this case, value1), then when you add another $ to $x (which becomes $$x), you are assigning value to the current value of $x (this equals to $value1='Peter')
To dynamically define a variable use $$. Demo
$sql = array("name"=>"Peter", "active"=>1 , "age"=>30);
$index = 1;
foreach($sql as $value){
${"value" . $index++} = $value;
}
You can easily get an key from a array but if I have the value, and I have the key,In array And wants boths, whats the best way to get it?
like :
$controller = $request->get('_controller');
$home = array('XXX\ABCBundle\Controller\PageHomeController::indexAction'=>5, 'XXX\ABCBundle\Controller\RegistrationController::confirmedAction'=>10);
First time I want key for compression and when this is inter then want to key:-
if(in_array($controller,$home)){
echo "blabla";
$point = $home[$controller];
}
But this is not working.
in_array searches for a value, but you're looking for a key. You should use array_key_exists for this, or isset($home[$controller]).
if (isset($home[$controller])) {
echo "blablah";
$point = $home[$controller];
}
how to slice an array to pass it to a function. I cannot use unset because I need that array further. I know I can copy whole array to variable, however it's quite big and don't thing it's efficient. My code:
$list = array(0=>2123, 2=>1231, 7=>123123,...);
unset($list[0]); //I can't do this because I still need whole $list
$seats = $allocatingClass->allocateSeats($seatsNumber, $list); //here I need to slice $key from $list and pass $list without reiterating
If you need to keep index 0, store it, rather than storing the entire array elsewhere:
$tmp = $list[0];
Then splice the array:
$list = array_splice($list,1,count($list));
Then pass it to your function:
$seats = $allocatingClass->allocateSeats($seatsNumber, $list);
Then, when you need it, put back the value to the array:
$list[] = $tmp;
Edit: if you actually need to put it exactly at index 0, then you may want to unset the index 0 of the array instead of splicing it. If you can, however, push it at the end of the array just follow what is written above.
To clearify, if you need to LATER push back the element to index 0, do
unset($list[0]);
instead of the splice...
And to put back the element, do:
$list[0] = $tmp;
However you do it, a copy will be made when passing the array (unless you pass it by reference).
either use splice. or create a copy and shift one value.
after sending the copy variable, you can unset it so it wont keeptaking its space.
Edit :
The above solution is also viable. Though I suggest you use:
$tmp = array_shift($arr);
doStuf($arr);
array_unshift($arr, $tmp);
My randomize function does not work properly.
I have an array which is getting randomized.
The array contains three values but only two are chosen each time.
$sterren = array("3","4","5");
$sterrenr = array_rand($sterren, 1);
$sterrenf = $sterren[$sterrenr[0]];
echo $sterrenf;
During the loop when outputting echo $sterrenf only the values 3 and 4 appear but no value 5.
Anyone any ideas ?
When the optional $num parameter is set, array_rand() returns $num random keys. In this case, you're setting the second parameter 1, so you'll get a single key. You just need to echo the corresponding array element:
Change:
$sterrenf = $sterren[$sterrenr[0]];
to:
$sterrenf = $sterren[$sterrenr];
Very easy look with:
First to retrieve the three elements point array_rand to (~,3) not to (~,1).
Second to random as you think is by shuffle in php not by array_rand because array_rand will return a random selection but will rearrange them inside it so after it use "shuffle()" on the output of array_rand "result array" like this what i mean:
$sterren = array("3","4","5");
$sterrenr = array_rand($sterren, 3);
shuffle($sterrenr);
$sterrenf = $sterren[$sterrenr[0]];
echo $sterrenf;
If I have:
$mainarray = some array of things with some repeated values
$array_counted = array_count_values ($mainarray);
How can I find the maximum value in $array_counted?
(This would be the element that appeared most often in $mainarray I think. Its mostly a syntax issue as I am pretty sure I could loop it, but not sure of the syntax to use)
You can find first max value as
$main_array = array(1,2,3,4,5,6,6,6,6,6,6,6);
$max_val = max($main_array);
for find all of max vals
in php < 5.3
function findmax($val)
{
global $max_val;
return $val == $max_val;
}
$max_values_array = array_filter($main_array,'findmax');
in php >= 5.3
$max_values_array = array_filter($main_array,function($val) use ($max_val) { return $val == $max_val; });
echo count($max_values_array);
var_dump($max_values_array);
You could sort the array and take the first, respectively last item out of it, if you don't want to loop.
Since you associate the count with the values with that:
$array_counted = array_count_values ($mainarray);
You only need to sort it afterwards, and return the first key (which is the most occured element):
arsort($array_counted);
print key($array_counted); // returns first key
ok, the guy whos answer I used has deleted his comment so here is how I did it:
I used arsort($array_counted) to sort the array, while keeping index. rsort alone does not work as the result of array_count_values is an associative array. Thank you all.