This code picks 2-6 pitches from the $vec array. I'd like to echo out each individual pitch, but interestingly enough, it gives me the numeric values of the placement of the pitch in the array (ie: 2 5 6 instead of D F F#)
$pick = rand(2,6);
$vec = array("C","C#","D","D#","E","F","F#","G","G#","A","A#","B");
$random_keys = array_rand($vec,$pick);
foreach ($random_keys as $pitch){
echo $pitch; echo "<br>";
}
Why is it doing this and how can I get the pitches instead of the numbers?
Try this:
$pick = rand(2,6);
$vec = array("C","C#","D","D#","E","F","F#","G","G#","A","A#","B");
$random_keys = array_rand($vec, $pick);
foreach ($random_keys as $key) {
echo $vec[$key], '<br />';
}
From array_rand() documentation:
Return value
If you are picking only one entry, array_rand() returns the key for a random entry. Otherwise, it returns an array of keys for the random entries. This is done so that you can pick random keys as well as values out of the array.
Related
I have the following array:
$array = [2,2,5,2,2];
I would like to get the number which is different from the others, for example all the numbers are 2 except the number 5. So Is there anyway to get the different number using any array method or better solution? My solution is:
$array = [2,2,5,2,2];
$array1 = [4,4,4,6,4,4,4];
$element = -1;
$n = -1;
$count = 0;
for($i=0; $i<count($array1); $i++) {
if($element !== $array1[$i] && $element !== -1 & $count==0) {
$n = $array1[$i];
$count++;
}
$element = $array1[$i];
}
dd($n);
You can use array_count_values for group and count same value like:
$array = [2,2,5,2,2];
$countarray = array_count_values($array);
arsort($countarray);
$result = array_keys($countarray)[1]; // 5
Since you only have two numbers, you will always have the number with the least equal values in second position
Reference:
array_count_values
array_keys
A small clarification, for safety it is better to use arsort to set the value in second position because if the smallest number is in first position it will appear as the first value in the array
Sorting Arrays
You can user array_count_values which returns array with item frequency.
Then use array_filter to filter out data as follow:
$arrayData = [2,2,2,5];
$filterData = array_filter(array_count_values($arrayData), function ($value) {
return $value == 1;
});
print_r($filterData);
Inside array_filter(), return $value == 1 means only get the data with 1 frequency and thus filter out the other data.
<?php
function UniqueAndDuplicat($array){
$counts = array_count_values($array);
foreach ($counts as $number => $count) {
print $number . ' | ' . ($count > 1 ? 'Duplicate value ' : 'Unique value ') . "\n";
}
}
$array1 = [2,2,5,2,2];
$array2 = [4,4,4,6,4,4,4];
UniqueAndDuplicat($array1);
//output: 2 | duplicate value 5 | Unique value
UniqueAndDuplicat($array2);
//output: 4 | duplicate value 5 | Unique value
?>
Use this function to reuse this you just call this function and pass an Array to this function it will give both unique and duplicate numbers.
If you want to return only Unique number then use the below code:
<?php
function UniqueAndDuplicat($array){
$counts = array_count_values($array);
foreach ($counts as $number => $count) {
if($count == 1){
return $number;
}
}
}
$array1 = [2,2,5,2,2];
$array2 = [4,4,4,6,4,4,4];
echo UniqueAndDuplicat($array1); // 5
echo "<br>";
echo UniqueAndDuplicat($array2); // 6
?>
I want to echo one element of the array like sum1. But I only get one letter like s. Please solve this problem.
$nums = array("sum1", 100, 200);
foreach ($nums as $value) {
echo $value[0];
echo $value[1];
}
If you want to just echo 1 item from that array, you should to it like this:
echo $nums[0];
If you want to loop through all of them, and show each, do it like so:
$nums = array("sum1", 100, 200);
foreach ($nums as $value) {
echo $value."<br>";
}
What you did wrong
You had already looped through the array, so you had a string. You can select the first letter from a string like in this example:
$string = "A string";
echo $string[0];
Will return A, as it's the first index of that string. That is essentially what you did in your loop.
You made your String an array, and it showed the index's you selected to be shown. You can read this where the questions asks how to do this. I hope this gives some more clearity.
If you want every element of array,
then,
For your array,
$nums = array("sum1", 100, 200);
$nums[0] will be sum1
$nums[1] will be 100
$nums[2] will be 200,
Now your loop,
foreach ($nums as $value) {
// here echo $value values are like 'sum1', 100, 200 will be printed.
// by default string will be considered as array,
// if you print $value[0], $value[1], $value[2], $value[3] for sum1, it will return, s, u, m, 1 respectively.
// and integers will be considered as pure value, which you will get in $value only, not in $value[0], ....
}
I hope I explained your concern.
Thanks.
I want to remove $win value from array and print all names except to winner. please check below code.
<html>
<p>
<?php
// Create an array and push on the names
// of your closest family and friends
$array=array();
array_push( $array,"preet");
array_push($array,"limbu");
array_push($array,"nik");
array_push($array,"rohit");
array_push($array,"ravi");
// Sort the list
sort($array);
echo"all guys are ".$f=join(", ",$array);
echo"<br>Lets see who is winner</br> ";
$len=count($array);
// Randomly select a winner!
$win=strtoupper( $array[rand(0,$len-1)]);
// Print the winner's name in ALL CAPS
echo "$win";
//print name of all except to winner.but given below code is not working
unset($win);
print"<br> sory ".join(",",$array);
You have to unset the entry of the winner in your $array
<?php
// Create an array and push on the names
// of your closest family and friends
$array = array();
array_push($array, "preet");
array_push($array, "limbu");
array_push($array, "nik");
array_push($array, "rohit");
array_push($array, "ravi");
// Sort the list
sort($array);
echo"all guys are " . $f = join(", ", $array);
echo"<br>Lets see who is winner</br> ";
$len = count($array);
// Randomly select a winner!
$random = rand(0, $len - 1);
$win = strtoupper($array[$random]);
// Print the winner's name in ALL CAPS
echo $win;
//print name of all except to winner.but given below code is not working
unset($array[$random]);
print"<br> sory " . join(",", $array);
You need to know the index of the value in the array to remove the item from the array.
You can do this using the array_search function and then use unset to remove the value.
if(($key = array_search($win, $array)) !== false) {
unset($array[$win]);
}
I have an associative array, $teams_name_points. The length of the array is unknown.
How do I access the first and forth value without knowing the key of this array in the easiest way?
The array is filled like this:
$name1 = "some_name1";
$name2 = "some_name2";
$teams_name_points[$name1] = 1;
$teams_name_points[$name2] = 2;
etc.
I want to do something like I do with an indexed array:
for($x=0; $x<count($teams_name_points); $x++){
echo $teams_name_points[$x];
}
How do I do this?
use array_keys?
$keys = array_keys($your_array);
echo $your_array[$keys[0]]; // 1st key
echo $your_array[$keys[3]]; // 4th key
You can use array_values which will give you a numerically indexed array.
$val = array_values($arr);
$first = $val[0];
$fourth = $val[3]
In addition to the array_values, to loop through as you show:
foreach($teams_name_points as $key => $value) {
echo "$key = $value";
}
You can get use the array_keys function such as
//Get all array keys in array
$keys = array_keys($teams_name_points);
//Now get the value for 4th key
//4 = (4-1) --> 3
$value = $teams_name_points[$keys[3]];
You can get all values now as exists
$cnt = count($keys);
if($cnt>0)
{
for($i=0;$i<$cnt;$i++)
{
//Get the value
$value = $team_name_points[$keys[$i]];
}
}
I have an array of about 100 different random number like this:
$numbers=array(10,9,5,12, ..... .... ... ...);
now i want to make an array of random numbers from this array so that addition of selected numbers will be my given number. example: i may ask to get array of numbers such that, if i add all numbers it will be 100.
i am trying to do it in this way,
function rendom_num ($array,$addition)
{
//here is the code
}
print_r (rendome_num ($numbers,100));
i am not able to fiend the code for last 3 days!
Please use shuffle-
<?php
$numbers = range(1, 20);
shuffle($numbers);
foreach ($numbers as $number) {
echo "$number ";
}
?>
php.net
can use shuffle as #chatfun said or can try array_rand if want only some random values from your array
$value= array("Rabin","Reid","Cris","KVJ","John");
$rand_keys=array_rand($value,2);
echo "First random element = ".$value[$rand_keys[0]];
echo "<br>Second random element = ".$value[$rand_keys[1]];
Something like this should work. The breakdown is commented so you know what it's all doing.
function Randomizer($number = 100)
{
// This just generates a 100 number array from 1 to 100
for($i=1; $i <= 100; $i++) {
$array[] = $i;
}
// Shuffles the above array (you may already have this array made so you would need to input into this function)
shuffle($array);
// Assign 0 as base sum
$sum = 0;
// Go through the array and add up values
foreach($array as $value) {
// If the sum is not the input value and is also less, continue
if($sum !== $number && $sum < $number) {
// Check that the sum and value are not greater than the input
if(($sum + $value) <= $number) {
// If not, then add
$sum += $value;
$new[] = $value;
}
}
// Return the array when value hit
else
return $new;
}
// If the loop goes through to the end without a successful addition
// Try it all again until it does.
if($sum !== $number)
return Randomizer($number);
}
// Initialize function
$test = Randomizer(100);
echo '<pre>';
// Total (for testing)
echo array_sum($test);
// Array of random values
print_r($test);
echo '</pre>';