PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
I was hoping to write some code to display the results of a poll but I want a string printed before each one, depending on which has the higher value. Prepare yourself for this code because it's a bit of a head twister:
if ($totalCplus > $totalJava && $totalCplus > $totalPhp) {
echo "C++ leads the vote with: <b>$totalCplus<br></b>"; }
if ($totalJava > $totalPhp ) {
echo "Java is in second place with:<b> $totalJava<br></b>";
echo "PHP lacks behind with:<b>$totalPhp<br></b>"; }
else {
echo "PHP is in second place with:<b> $totalPhp<br></b>";
echo "Java lacks behind with:<b> $totalJava<br></b>";
}
if ($totalJava > $totalCplus && $totalJava > $totalPhp) {
echo "Java leads the vote with: <b>$totalJava<br></b>"; }
if ($totalCplus > $totalPhp) {
echo "C++ is in second place with:<b> $totalCplus<br></b>";
echo "PHP lacks behind with:<b>$totalPhp<br></b>"; }
else {
echo "PHP is in second place with:<b> $totalPhp<br></b>";
echo "C++ lacks behind with:<b>$totalCplus<br></b>";
}
if ($totalPhp > $totalJava && $totalPhp > $totalCplus) {
echo "PHP leads the vote with: <b>$totalPhp<br></b>"; }
if ($totalJava > $totalPhp) {
echo "Java is in second place with:<b> $totalJava<br></b>";
echo "C++ lacks behind with:<b> $totalCplus<br></b>"; }
else {
echo "Cplus is in second place with:<b> $totalCplus<br></b>";
echo "Java llacks behind with:<b> $totalJava<br></b>";
}
Why don't you put the variables in an array with keys as the programming languages, sort the array and tehn echo the key and its value with the text. Would look neater.
andym01480 wrote:Why don't you put the variables in an array with keys as the programming languages, sort the array and tehn echo the key and its value with the text. Would look neater.
$allVotes = array (
'php'=>500000000000000000000,
'java' => 12,
'cpp' =>5000
);
asort($allVotes);
foreach ($allVotes as $language=>$votes) {
echo "The Language {$language} received a total of {$votes} votes.<br/>";
}
What I've posted is just an example to get you started. If you want to make any changes then I suggest you tinker with the script and see what happens. You'll learn much more that way than if I just tell you.
Am I correct in thinking that's a 2-D array you've used in your example? I havn't jumped too far into 2Ds but I know it's something I'll be facing in the future.
It's an array of associative arrays. That's then broken down into 2 seperate associative arrays with indexes that are the same for each element. Then those are fed into array_multisort() which rebuilds the original array of associative arrays nicely sorted into the right order.