I'm new to php and I wrote a code that takes a random winner out of an array and displays it, then I wanted to try to display all the names without the winner's, but how can I unset the winner by using the random number generated? I managed to unset a random name but not the same as the winner...
<?php
// array
$winner = array();
array_push($winner,"sonia");
array_push($winner,"ice");
array_push($winner,"sasha");
array_push($winner,"isa");
array_push($winner,"omar");
array_push($winner,"anwar");
// random winner
$giocatori = count($winner);
$random = rand(0,$giocatori -1);
unset($winner[$random]);
// Sort the list
sort($winner);
echo "I giocatori sono: ";
print join(", ",$winner);
// Print the winner's name in ALL CAPS
$truewinner = strtoupper($winner[$random]);
echo "<br><br>";
echo "il vincitore รจ: ";
// Print winner + sentence
$losers = "losers";
$losers = strtoupper($losers);
echo (strtoupper($winner[$random]));
echo "<br><br>";
echo "all the players are: $losers beside $truewinner";
?>
$players = array('sonia', 'ice', 'sasha', 'isa', 'omar');
$random = rand(0, count($players) - 1);
$winner = $players[$random];
$losers = array_diff($players, array($winner));
echo 'All players are: ' . implode(', ', $players);
echo 'Winner is: ' . $winner;
echo 'Losers are: ' . implode(', ', $losers);
How to write the array:
$participants = array("sonia", "ice", "sasha","isa","omar","anwar");
or
$participants = array();
$participants[] = "sonia";
$participants[] = "ice";
and soo on
//make all participants name first letter uppercase
$participants = array_map(function($string) {return ucfirst($string);},$participants);
To get an random value from the array you have:
//get a random key
$random = array_rand($participants);
//get the value for the key
$winner = $participants[$random];
//unset the key and value
unset($participants[$random]);
OR
//this will shuffle values in the array on random positions
shuffle($participants);
//this return the last value from the array and deletes it from the array
$winner = array_pop($participants);
echo "The winner is $winner !\n";
echo "The losers are ".implode(', ',$participants)."\n";
<?php
// array
$winner = array();
array_push($winner,"sonia");
array_push($winner,"ice");
array_push($winner,"sasha");
array_push($winner,"isa");
array_push($winner,"omar");
array_push($winner,"anwar");
// random winner
$giocatori = count($winner);
$random = rand(0,$giocatori -1);
echo "winner is".$winner[$random];
unset($winner[$random]);
// Sort the list
sort($winner);
echo print_r($winner) ;
echo "losers are ";
foreach($winner as $res) {
echo $res. ' ';
}
?>
Output
winner is anwar
Array
(
[0] => ice
[1] => isa
[2] => omar
[3] => sasha
[4] => sonia
)
losers are ice isa omar sasha sonia
Related
i have following array values, here spend is repeated,
$array = array('Spend','Spend','Form Conversions','Phone Conversions')
i can detect multiple entries like this
print_r(array_count_values($array));
output is
Array
(
[Spend] => 2
[Form Conversions] => 1
[Phone Conversions] => 1
)
how can i put separate condition to print as follows
if(any key(here spend) found with count = 2 )
{
echo $duplicate element; //edits
}
else
{
echo $no_duplicate_elements //edits
echo "count = 1 (here Form Conversions,Phone Conversions)";
}
how about
foreach(array_count_values($array) as $value => $count){
if($count > 1){
echo "hi " . $value . "*";
}else{
echo "count = 1 " . $value . "*";
}
}
?
use function in_array
if (in_array(2, array_count_values($array))) {
echo "there is at least one word with count = 2";
}
if you want to know what elements are duplicated, then you have to use foreach - check Jameson the dog's answer.
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 don't speak very good English, not sure about title so will try to explain what i need to do:
I am making log parser.
I have 3 dynamic arrays (read from .log file) containing corresponding elements:
$personName //array of strings, can contain same name
$itemName //array of strings, can contain same name
$itemAmount //array of numbers
Sample arrays:
$personName = array("Adam", "Maria", "Adam", "Adam");
$itemName = array("paper", "paper", "pen", "paper");
$itemAmount = array(11, 25, 2, 64);
I would like to sort (by person and item) and count (by amount) those arrays, eg. to print:
Total there are '100' 'paper' and '2' 'pen'.
'Adam' have '75' 'paper' and '2 'pen'.
'Maria' have '25' 'paper'.
This would allow me to get % of each item each person have, eg.:
'Adam' have '75'% of all 'paper' and '100'% of all 'pen'.
'Maria' have '25'% of all 'paper'.
I have arrays with unique names:
$persons = array_keys (array_flip ($personName));
$items = array_keys (array_flip ($itemName));
I did tried different combinations of for loops with foreach, but I struggle to find any solution.
Can somebody help me to get right approach?
(sorry if this is too basic, i really tried to look for solution and I'am very new to programming, started learning 3 days ago with this project)
Thanks!
Like this:
<?php
$personName = array("Adam", "Maria", "Adam", "Adam", "Mihai");
$itemName = array("paper", "paper", "pen", "paper", 'pencil');
$itemAmount = array(11, 25, 2, 64, '18');
$items = array();
$persons = array();
foreach($itemName as $id => $name){
$items[$name] += $itemAmount[$id]; // we are adding amount for each item to $items array
$persons[$personName[$id]][$name] += $itemAmount[$id]; // we are adding every item with amount to each persons
}
echo "Total there are "; // we are looping in each $items to display totals
$i = 0;
foreach($items as $nr => $item){
echo "'".$item."' '".$nr."'";
if($i < count($items)-2){ // this is for 'and' or ',' in case of multiple items
echo ", ";
} elseif($i < count($items)-1){
echo " and ";
}
$i++;
}
echo '<br />';
foreach($persons as $one => $value ){ // we are looping in each persons to display what they have
echo "'".$one."' have ";
$i = 0;
foreach($value as $val => $number){
echo "'".$number."' '".$val."'";
if($i < count($value)-2){ // this is for 'and' or ',' in case of multiple items
echo ", ";
} elseif($i < count($value)-1){
echo " and ";
}
$i++;
}
echo '.<br />';
}
// print_r($items); // will result in all items
// print_r($persons); // will result in every person with every item
?>
Now you can manage %.
I am attempting to generate a weekly email to users of my site that lists locations that have added new information. When someone adds information, a table receives two numbers, one for the state and the second for the county. The first step of my cron job is to take the numbers and convert them to county, state format (Alameda, California for example). At the end of each conversion I added a | to be used as a delimiter. This part works perfectly. Next I loop through each user to send this information via email but this part does not work. What I end up with is the word array instead of my county, state format. What am I missing?
This is the code that performs the 1st step, which works just fine:
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$SID = $row['SID'];
$CID = $row['CID'];
$states = mysql_query("SELECT * FROM State WHERE ID = '$SID'");
while ($state = mysql_fetch_array($states)) {
$statename = $state['Name'];
}
$countys = mysql_query("SELECT * FROM County WHERE ID = '$CID'");
while ($county = mysql_fetch_array($countys)) {
$countyname = $county['Name'];
}
$locations = '<a href="http://hammerpins.net/display.php?state=' . $SID .' &county=' . $CID .'" >' . "$countyname, $statename ". '</a>' . "|";
$i = $i + 1;
}
This is the code that I am using to explode the array into the county, state format, which does not function properly. Instead I get the word array.
$locals = explode("|", $locations);
$locals is used in the email message as the list of new information. Please point me in the right direction. Thanks
explode will give you array
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
so when you use explode function, it will explode string in to array
in your case .. write
$locals = explode("|", $locations);
echo "<pre>";print_r($locals);echo "</pre>";
and you will have exact idea and it will solve your problem
First, what is the purpose of $i?
Second, I think you want to concatenate $locations:
// This overwrites the variable - this is what you are doing
// at the end $locations will be the one single last link
$locations = '<a href="ht
// This adds to / concatenates - giving you a long strong of many links
$locations .= '<a href="ht
// ^ Note the period.
Third, explode does take a string and turns it into an array.
If you're making a long string, why would you want to explode it back into the parts you constructed it from?
I would suggest storing your states, countys, and constructed links in arrays. Then you can use the contents of those arrays at will to create your emails.
To look at what's in an array use print_r() or var_dump(). You can loop over arrays with foreach().
<?php
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$SID = $row['SID'];
$CID = $row['CID'];
$states = mysql_query("SELECT * FROM State WHERE ID = '$SID'");
while ($state = mysql_fetch_array($states)) {
// There had better only be ONE statename per SID or you lose info!
$user_array[$i]['statename'] = $state['Name'];
}
$countys = mysql_query("SELECT * FROM County WHERE ID = '$CID'");
while ($county = mysql_fetch_array($countys)) {
// There had better only be ONE countyname per CID or you lose info!
$user_array[$i]['countyname'] = $county['Name'];
}
$user_array[$i]['link'] = '<a href="http://hammerpins.net/display.php?state=' . $SID .' &county=' . $CID .'" >' . "{$user_array[$i]['countyname']}, {$user_array[$i]['statename']} ". '</a>';
++$i; // add one to i
}
// Show the arrays:
echo "<pre>";
print_r($user_array);
echo "</pre>";
?>
The above gives you an array like
Array
(
[0] => Array
(
[statename] => CA
[countyname] => San Bernardino
[link] => <a href="blah...
)
[1] => Array
(
[statename] => OR
[countyname] => Multnomah
[link] => <a href="yada...
)
)
To use the array just do
foreach ($user_array as $single_user_item) {
echo $single_user_item['link'];
}
Hope you are fine. My question :
In MYSQL i have a table with this type of field
Field Name: TAGS
Value : xavier,celine,marise,leon,john,cathy,polux,maurice
In PHP i do this
$xwords = array();
function array_rpush(&$arr, $item)
{
$arr = array_pad($arr, -(count($arr) + 1), $item);
}
$tags = requete("SELECT tags FROM tbl_tags LIMIT 1;");
while($dtags = mysql_fetch_assoc($tags)){
$words .= array_rpush($xwords, $dtags['tags']);
}
// MY ARRAY XWORDS FOR DEBUG
//
// Array ( [0] => xavier, celine, marise, leon, john, cathy, polux, maurice
//
My script need to find the first letter of each word in this list and check if he match with A / B / C (i create an A-Z index page)
// COUNT $XWORDS VALUE
$total = count($xwords);
// total =1
for($i=0; $i < $total; $i++)
{
$wtags = explode(",",$xwords[$i]);
// wtags = Array ( [0] => xavier [1] => celine [2] => marise... )
while (list($idx,$val) = each($wtags)) {
echo $val{0}."<br>";
echo substr($val,0,1)."<br>";
}
}
echo $val{0}."<br>"; OR echo substr($val,0,1)."<br>" give me just x and nothing after (while give me only the first letter for the first record in array... amazing :))
Perhaps you can help me find a solution. Thanks
The problem with your code is that it generates:
Array ( [0] => "xavier" [1] => " celine" [2] => " marise"... )
So $val[0] = " ". Try to trim($val):
$val = trim($val);
print $val[0];
$sum = array();
foreach($wtags as $tag){
$tag = trim($tag);
empty($sum[$tag{0}]) ? // if we don't have a $sum element for this letter
$sum[$tag{0}] = 1 : // we initialize it
$sum[$tag{0}]++; // else, we sum 1 element to the count.
//$tag{0} is the first letter.
}
// the array $sum has the total of tags under each letter
//
// $sum[x] = 1
// $sum[c] = 2
// $sum[m] = 2
// $sum[l] = 1
// $sum[j] = 1
// $sum[p] = 1