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]);
}
Related
I have the following string
$ickkcids = "120,176,182,120,182,207,176,120,182,118,120,176";
I want to display it in a ascending ordered, like below.
118(1) //118 is the lowest integer so it comes first.
120(4)
176(3)
182(3)
207(1) //207 is the highest integer so it comes last.
This is what im doing
$array = explode(',', $ickkcids);
sort($array);
foreach($array as $arraye)
{
$html .= $arraye.'<br />';
}
But this returns all numbers in ascending order and i don't know how to count in this.
Any idea how to achieve this?
I support all above comments.First try your self, then ask a question.
Any way #OITE OMAN, you can try this code for your question:
$str = "120,176,182,120,182,207,176,120,182,118,120,176";
$array = explode(",",$str);
asort($array, SORT_NUMERIC);
$latest_array = array_count_values($array);
print_r($latest_array);
foreach($latest_array as $key=>$value){
echo $key."(".$value.")";
echo "</br>";
}
Output:
118(1)
120(4)
176(3)
182(3)
207(1)
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>';
In the first time, I'm sorry for my disastrous english.
After three days trying to solve this, i give up.
Giving this array:
$names = array ( "James Walter Case", "Benjamin Wallace Pinkman", "Billy Elliot Newson" )
I have to extract the full name of the higher first stringlength word of each full name.
In this case, considering this condition Benjamin will be the higher name. Once
this name extracted, I have to print the full name.
Any ideas ? Thanks
How about this?
$names = array ( "James Walter Case", "Benjamin Wallace Pinkman", "Billy Elliot Newson" );
if (count($names) > 0)
{
$higher_score = 0;
foreach ($names as $name_key => $name_value)
{
$name_array = explode(" ", $name_value);
// echo("<br><b>name_array -></b><pre><font FACE='arial' size='-1'>"); print_r($name_array); echo("</font></pre><br>");
$first_name = $name_array[0];
// echo "first_name -> ".$first_name."<br>";
$score = strlen($first_name);
// echo "score -> ".$score."<br>";
if ($score > $higher_score)
{
$higher_score = $score;
$winner_key = $name_key; }
}
reset($names);
}
echo("longest first name is ".$names[$winner_key]." with ".$higher_score." letters.");
As said before, you can use array_map to get all the lenghts of the first strings, and then get the name based on the key of that value.
$names = array ( "James Walter Case", "Benjamin Wallace Pinkman", "Billy Elliot Newson" );
$x = array_map(
function ($a) {
$x = explode (" ", $a); // split the string
return strlen($x[0]); // get the first name
}
, $names);
$maxs = array_keys($x, max($x)); // get the max values (may have equals)
echo $names[$maxs[0]]; // get the first max
-- EDIT
Actually, there is a better way of doing this, considering this case. You can simply order the array by the lenght of the first names, and then get the first key:
usort($names,
function ($a, $b) {
$aa = explode(" ", $a); // split full name
$bb = explode(" ", $b); // split full name
if (strlen($aa[0]) > strlen($bb[0])){
return 0; // if a > b, return 0
} else {
return 1; // else return 1
}
}
);
echo $names[0]; // get top element
Allow me to provide a handmade solution.
<?php
$maxLength = 0;
$fullName = "";
$parts = array();
foreach($names as $name){
/* Exploding the name into parts.
* For instance, "James Walter Case" results in the following array :
* array("James", "Walter", "Case") */
$parts = explode(' ', $name);
if(strlen($parts[0]) > $maxLength){ // Compare first length to the maximum.
$maxLength = strlen($parts[0]);
$fullName = $name;
}
}
echo "Longest first name belongs to " . $fullName . " (" . $maxLength . " character(s))";
?>
Basically, we iterate over the array, split each name into parts (delimited by spaces), and try to find the maximum length among first parts of names ($parts[0]). This is basically a maximum search algorithm.
There may be better ways with PHP array_* functions, but well, this one gets pretty self-explanatory.
You can try something like..
$maxWordLength=0;
$maxWordIndex=null;
foreach ($names as $index=>$name){
$firstName=first(explode(' ',$name));
if (strlen($firstName)>maxWordLength){
$maxWordLength=strlen($firstName);
$maxWordIndex=$index;
}
}
if ($maxWordIndex){
echo $names[$maxWordIndex];
}
I have a table that I need to find "top trusted builder" from, Trusts are separated by " ; ", So I need to pull all the data, explode the usernames, order and count them, and Im stuck on finally outputting the top username form the array, I have posted up the full segment of PHP, because im sure there has to be a much better way of doing this.
<?php
$GTB = $DBH->query('SELECT builders from griefprevention_claimdata where builders <> ""');
$GMCB->setFetchMode(PDO::FETCH_ASSOC);
$buildersarray = array();
while($row = $GTB->fetch()) {
$allbuilders = explode(";", $row['builders']);
for($i = 0; $i < count($allbuilders); $i++)
{
$buildersarray[] = $allbuilders[$i];
}
}
echo "<pre>";
print_r(array_count_values(array_filter($buildersarray)));
echo "</pre>";
?>
Outputs
Array
(
[username1] => 4
[username2] => 1
[username3] => 1
)
You can return the array from the array_count_values command into a new array called $topbuilders, and then echo out the current (first) record:
$topbuilders = array_count_values(array_filter($buildersarray));
echo current(array_keys($topbuilders)).', Rank = '.current($topbuilders);
current() will return the first item in an associative array.
Instead of using array_count_values() it would be better to use the names as the key to a frequency array:
$GTB = $DBH->query('SELECT builders from griefprevention_claimdata where builders <> ""');
$result = array();
while (($builders = $GTB->fetchColumn()) !== false) {
foreach (explode(";", $builders) as $builder) {
if (isset($result[$builder])) {
$result[$builder]++;
} else {
$result[$builder] = 1;
}
}
// sort descending based on numeric comparison
arsort($result, SORT_NUMERIC);
echo "Name = ", key($result), " Count = ", current($result), "\n";
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.