Create a loop using associative arrays - php

I want to put this in a loop because it needs to be repeated 6 times, is it true that using variable variables is a bad practice? Do I need associative arrays?
Basically the 'c1' inside the variable needs to progressively change into 'c2', 'c3'...etc
<?php if ($pm_c1_djwd !== '') { ?>
<div>
<span style="width:<?php echo $pm_width_c1;?>%"></span>
<span><?php echo $pm_description_c1; ?></span>
</div>
<?php } ?>
Many Thanks

Why not try regular arrays?
<?php
// Warning: Typed raw in the textarea
$pm_width = array(100, 100, 100, 100, 100, 100);
$pm_description = array(
"Gizmo",
"Doodad",
"Widget",
"Dohicky",
"Thing-me-a-bob",
"Marvelous toy my father gave to me."
);
$pm_c1_djwd = "Snod";
if ($pm_c1_djwd !== '') {
for ($i = 0; $i < count($pm_description); $i++) {
$width = $pm_width[$i];
$desc = $pm_description[$i];
echo "<div>";
echo "<span style='width:${width}%'>$desc</span>";
echo '</div>';
echo PHP_EOL;
}
}
?>

Instead of having a variable for each field like $pm_description_c1, ..c2 and so on, put them in an associative array:
$pms = array(
array('description' => 'your description', 'width' => '123px', 'djwd' = 'what'),
array('description' => 'Second item', 'width' => '123px', 'djwd' = '')
);
Then loop through them:
<?php
foreach ($pms as $pm) {
if ($pm['djwd' !== '') {
?>
<div>
<span style="width:<?php echo $pm['width'];?>%"></span>
<span><?php echo $pm['description']; ?></span>
</div>
<?php
}
}
?>

You can use variable variables for the thing you are asking...
<?php
$i = 0;
while( $i < 6 ){
$i ++;
$variable = "pm_c".$i."_djwd";
$variable2 = "pm_description_c".$i."";
if (isset($$variable) && $$variable != '') { ?>
<div>
<span style="width:<?php echo $$variable;?>%"></span>
<span><?php echo $$variable2; ?></span>
</div>
<?php }
}

Related

php how to do a loop to calculate score for a quiz website

i am creating a quiz website using php where there are 4 questions for users to answer. there is a home page before this for them to choose either math or lit that they wish to do.
after selecting the subject, user need to answer the question and submit their answer, then the php code will calculate their score and count the number of correct/wrong answers.
<ArrayquesAns.php> is the array of questions and answers
it looks something like this, there are 2 array in this php, 1 is math question and another 1 is lit question
and here is the main code where it will generate questions from the question pool randomly. i also tried to put in the code to calculate score
<html>
<body>
<?php
require_once 'ArrayQuesAns.php'; //retrieve array of ques
$_SESSION["subject"] = $_GET['subject']; //suppose to put value when session starts
$_SESSION["name"] = $_GET['name'];
$subject = $_SESSION["subject"];
$name = $_SESSION["name"];
$url = "displayScore.php?name=" . $name . "&subject=" . $subject . "&";
if ($subject == "mathematics") { //math session
$mathQues_key = array_rand($Mathques, 4); //Pick 4 random rows in array
$MathquesRand = array(); //New array to contain the 4 random rows
$i = 0;
foreach ($mathQues_key as $key) {
$MathquesRand[$i] = $Mathques[$key];
$i++;
}
?>
<form action="<?= $url ?>" method="get">
<h1> Section : <?= $subject ?> </h1>
<p>Hello <?= $name ?>! You may start your quiz !<p>
<hr>
<?php foreach ($MathquesRand as $qtsno => $value) { ?>
<?php echo $value["ques"] . " = \t"; ?> <!--Display Question -->
<input type="text" name="userans" value="<?php echo isset($_GET["userans"]) ? $_GET["userans"] : ''; ?>">
<br>
<?php } ?>
<?php
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
?>
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
} else { //Lit Section
$LitQues_key = array_rand($Litques, 4);
$LitquesRand = array();
$i = 0;
foreach ($LitQues_key as $key) {
$LitquesRand[$i] = $Litques[$key];
$i++;
}
?>
<form action="<?= $url ?>" method="get">
<h1> Section : <?= $subject ?></h1>
<p>Hello <?= $name ?> ! You may start your quiz !<p>
<hr>
<?php foreach ($LitquesRand as $qtsno => $value) {
echo $value["ques"], " = \t";
?> <!--Display Question -->
<input type="text" name="userans" value="<?php echo isset($_GET["userans"]) ? $_GET["userans"] : ''; ?>">
<br>
<?php } ?>
<?php
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
?>
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
}
?>
<!--Exit-->
<button type="button">EXIT</button>
</body>
</html>
i think this part is where it has issue
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
the code should match user input answer with array question/answer to see if the answer is correct. every correct question will *5 and every wrong answer will *3 (the formula is in the code).
i am not sure if i place the code in the wrong bracket hence its not working or there is some logic error or should i run the code to find the score in a separate php?
after user submit their answer, it will redirect to another page that display their score and number of correct/wrong answers like this
score display html
Based on your original version of the MC test, please find below a working version:
To make it simple, I have removed the "Name" and "Subject" of the form to demonstrate the necessary coding.
You can still use the array_rand to draw 4 random questions
However, after the questions are displayed to the student (and student can input the answer) and clicked "Submit Attempt", the page will remember the random questions drawn - I have used a trick :- to store the questions randomly drawn into a hidden input box
The system will compare the student's submitted answer with that of the correct answer and determine whether it is correct or wrong, and show the score
To fix the "undefined array" errors you encountered, I applied the isset function on places relating to the $_GET variables. (Actually these are warnings, not errors, but it is for sure a good practice to use isset)
<?php
//require_once 'ArrayQuesAns.php'; //retrieve array of ques
$Mathques=array(
1=> array('no'=>1, 'ques'=>"3+1", 'ans'=>"4"),
2=> array('no'=>2, 'ques'=>"3+3", 'ans'=>"6"),
3=> array('no'=>3, 'ques'=>"3+4", 'ans'=>"7"),
4=> array('no'=>4, 'ques'=>"3+5", 'ans'=>"8"),
5=> array('no'=>5, 'ques'=>"3+6", 'ans'=>"9"),
6=> array('no'=>6, 'ques'=>"3+7", 'ans'=>"10"),
7=> array('no'=>7, 'ques'=>"3+8", 'ans'=>"11"),
8=> array('no'=>8, 'ques'=>"3+9", 'ans'=>"12"),
9=> array('no'=>9, 'ques'=>"3+10", 'ans'=>"13"),
10=> array('no'=>10, 'ques'=>"3+11", 'ans'=>"14")
);
if (! isset($_GET["draw"])) {
$mathQues_key = array_rand($Mathques, 4); //Pick 4 random rows in array
}
$MathquesRand = array(); //New array to contain the 4 random rows
if (! isset($_GET["draw"]) ) {
$i = 0;
foreach ($mathQues_key as $key) {
$MathquesRand[$i] = $Mathques[$key];
$i++;
}
}
?>
<?php
if (isset($_GET["draw"]) && $_GET["draw"] !="") {
$pieces = explode(",", $_GET["draw"]);
$index=0;
while ($index < count($pieces)) {
if ($pieces[$index]!=""){
$MathquesRand[] = $Mathques[$pieces[$index]];
}
$index++;
}
}
?>
<form action="" method="get">
<?php
$correct=0;
$wrong=0;
?>
<h1> Section : Mathematics </h1>
<p>Hello ! You may start your quiz !<p>
<hr>
<?php
$pool="";
$ii=1;
foreach ($MathquesRand as $qtsno => $value) {
$pool.= $value["no"]. ",";
?>
<?php echo $value["ques"] . " = \t"; ?> <!--Display Question -->
<input type="text" name="userans<?php echo $ii; ?>"
<?php if (isset($_GET["userans".$ii]))
{
echo " value='" .$_GET["userans".$ii] . "'>" ;
} else { echo ">" ; }
?>
<?php if (isset($_GET["userans".$ii]) && $_GET["userans".$ii]==$value["ans"]) {
$correct++;
} else {
$wrong++;
}
?>
<br>
<?php
$ii++;
}
?>
<input name=draw type=hidden value="<?php echo $pool; ?>">
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
$score = ($correct * 5) - ($wrong * 3);
?>
<?php if (isset($_GET["draw"])) { ?>
<font color=red>Result:</font>
<br>Correct:<?php echo $correct;?>
<br>Wrong:<?php echo $wrong;?>
<br>Score:<?php echo $score;?>
<?php } ?>
To share my experience (I have coded such Multiple Choice Q & A functions many times) , in future if you want to do similar thing, please consider using
database to store the drawn questions ;
use ajax to compare the input data with the correct data stored in the db, instead of using form submission

show div tag in php statement

I am now working on a WordPress theme base with the Advanced Custom Fields plugin, And I want to show a <div> tag when the if statement is true. Here is my code:
<?php
$rows = get_field('classification');
$sort = get_sub_field('sort');
$row_count = count($rows);
for ($i = 1; $i <= $row_count; $i++)?>
<?php if ( $i==1 || $i%5==0) { ?>
<div class="bor"></div>
<h3 style="text-align:center">
<?php echo $sort; ?>
<a id="browser"></a></h3>
<div class="bor"></div>
<?php } ?>
or something like that
<?php
$rows = get_field('classification');
$fenlei = get_sub_field('fenlei');
$row_count = count($rows);
for ($i = 1; $i <= $row_count; $i++)?>
<?php if ( $i==1 || $i%5==0) { ?>
echo '<div class="bor"></div>';
echo '<h3 style="text-align:center">';
<?php echo $fenlei; ?>
echo '<a id="browser"></a></h3>';
<div class="bor"></div>
<?php } ?>
But the content of the div tag doesn't show.
Any reply is appreciated!Thank you very much.
some of your echo statement are out php tags. use this:
<?php
$rows = get_field('classification');
$fenlei = get_sub_field('fenlei');
$row_count = count($rows);
for ($i = 1; $i <= $row_count; $i++){
if ( $i==1 || $i%5==0) {
echo "<div class='bor'></div>
<h3 style='text-align:center'>".$fenlei."
<a id='browser'></a></h3>
<div class='bor'></div>";
}
}
?>
If you wanted to show the html in php, i suggest you use the below code.
<?php
$rows = get_field('classification');
$fenlei = get_sub_field('fenlei');
$row_count = count($rows);
for($i = 1; $i <= $row_count; $i++){
if ( $i==1 || $i%5==0) {
echo '>div class="bor"<>/div<';
echo '>h3 style="text-align:center"<';
echo $fenlei;
echo '>a id="browser"<>/a<>/h3<';
echo '>div class="bor"<>/div<';
}
}
?>
I'm guessing you're using an ACF Pro Repeater field. in this case you need to use the_row() which will set the sub-field's correct content. look at this edited example from the Docs:
<?php
// check if the repeater field has rows of data
if( have_rows('repeater_field_name') ):
// loop through the rows of data
while ( have_rows('repeater_field_name') ) : the_row();
// display a sub field value
the_sub_field('sub_field_name');
endwhile;
endif;
?>
so, I think your code should look more like:
<?php
if(have_rows('classification')):
while (have_rows('classification') ) : the_row();
// Your Code...
endwhile;
endif;
?>
And, I've learned recently you need to count the rows outside the while loop. othewise it won't catch the rows amount.

How to give 3 different color for div's in loop in php

Trying to give 3 different color for div's in loop in php, now its working only two .how can i impliment alternative color for div.? Here what I want.
style
.redBackground { background-color:#F00; }
.blueBackground { background-color:#03F;}
.greenBackground { background-color:#6F3; }
php
<?php
$new= mysql_query("select * from tbl_news");
while ($row=mysql_fetch_array($new))
{
$x++;
$class = ($x%2 == 0)? 'redBackground': 'blueBackground' ;
echo "<tr class='$class'>";
$id = $row['id'];
$news = $row['news'];
?>
<div class="col-md-2 col-sm-12 col-xs-12 news_main_div">
<div class="md-trigger" data-modal="modal-11">
<div <?php echo "<tr class='$class'> ";?>>
<h1 style=" margin-bottom:5px;">
<strong ><?php echo $news ?></strong>
</h1></div></div><?php } ?>
Use color array like below
$color_array = array('whiteBackground', 'grayBackground', 'blueBackground');
$x=0;
while($row=mysql_fetch_array($new)){
$x++;
$class = $color_array[$x%3];
}
And in future, if you want to more color, then simply add color-class in array and change in $color_arrar[$x%n], where n=number_of_color
If you want random color, then use below code
$color_arrar = array('whiteBackground ','grayBackground ','blueBackground ');
$size_of_array = sizeof($color_arrar);
while($row=mysql_fetch_array($new)){
$n = rand(0,$size_of_array-1);
$class = $color_arrar[$n%3];
}
Please try this
if($x%3 == 0)
$class = 'greenBackground';
else if($x%2 == 0 )
$class = 'redBackground';
else
$class = 'blueBackground';
If you need it in random order you can use array_rand function
$color = array("redBackground", "blueBackground", "greenBackground");
$colorValue = array_rand($color, 1);
$class = $color [$colorValue];

wordpress random tag issue

I am having issue with a wordpress Tag CLoud Plugin.
I want to show random tags but i am confused how to do this.
the codes are given below.
I want to show random tags. like if i select to show just 5 tags and when each time i refrest the screen the tags should appear randomly.
function widget_tagcloud($args){
$option_value = retrieve_options($opt_val);
extract($args);
echo $before_widget;
echo $before_title;
echo $option_value['title'];
echo $after_title;
global $wpdb;
$tags_list = get_terms('post_tag', array(
'orderby' => 'count',
'hide_empty' => 0
));
if(sizeof($tags_list)!=0){
$max_count = 0;
if(!empty($option_value['height'])) $canvas_height = $option_value['height'];
else $canvas_height = "250";
if(!empty($option_value['width'])) $canvas_width = $option_value['width'];
else $canvas_width = "250";
foreach($tags_list as $tag) if($tag->count > $max_count) $max_count = $tag->count;?>
<div id="myCanvasContainer">
<canvas width="<?php echo $canvas_width;?>" height="<?php echo $canvas_height;?>" id="myCanvas">
<p>Tags</p>
</canvas>
</div>
<div id="tags">
<ul style="
font-family: <?php if(!empty($option_value['font_name'])) echo $option_value['font_name'];
else echo "Calibri";?>;
height:
<?php
if(!empty($option_value['height'])) echo $option_value['height'];
else echo "250";
?>px;
width:
<?php
if(!empty($option_value['width'])) echo $option_value['width'];
else echo "250";
?>px;
background-color: #<?php if(!empty($option_value['bg_color'])) echo $option_value['bg_color'];
else echo "FFF";?>;
">
<?php
if(empty($option_value['no_of_tags'])) $option_value['no_of_tags'] = 15;
if(empty($option_value['txt_color'])) $option_value['txt_color'] = "000";
if(empty($option_value['max_font_size'])) $option_value['max_font_size'] = 40;
if(empty($option_value['min_font_size'])) $option_value['max_font_size'] = 3;
$i=1;
foreach($tags_list as $tag){
if($i <= $option_value['no_of_tags']){
$font_size = $option_value['max_font_size'] - (($max_count - $tag->count)*2);
if($font_size < $option_value['min_font_size']) $font_size = $option_value['min_font_size'];
echo '<li><a href="'.$_SERVER['PHP_SELF'].'?tag='.$tag->slug.'"
style="font-size:'.$font_size.'px;color: #'.$option_value['txt_color'].';">'
.$tag->name.'</a></li>';
$i++;
}
}
echo '</ul></div>';
}
else echo "No tags found";
echo $after_widget;
}
Accordind to your code: (this part especially)
$tags_list = get_terms('post_tag', array(
'orderby' => 'count',
'hide_empty' => 0
));
The tags which you get are ordered by count , therefore - they are not randomly picked.
You can try and use the next code:
$tags_list = get_terms('post_tag', array(
'number' => 5,
'orderby' => 'none',
'hide_empty' => 0
));
And if that doesn't work , build a customized query using the RAND function of mysql.
EDIT: based on your code , you can do is even easier by using the shuffle() php function.
Just replace:
$max_count = 0;
With:
$max_count = 5;
shuffle($tags_list);

serial number for faq displayed from admin

I am using the following code for display questions and answers from admin.
<?php
$select_faq = "Select `intFaqid`, `varQuestion`,`varAnswer` FROM `tbl_faq`";
$selectfaq_result = mysql_query($select_faq);
$select_faqnum = mysql_num_rows($selectfaq_result);
if($selectfaq_result > 0)
{
while($fetch_faq = mysql_fetch_array($selectfaq_result))
{
$faqid = $fetch_faq['intFaqid'];
$fquestion = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varQuestion']))));
$fanswer = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varAnswer']))));
?>
<h3><?php echo $fquestion; ?></h3>
<p><?php echo $fanswer; ?></p>
<?php
}
}
?>
I need to display the question number before the question. I used the following code for display the question number.
<?php
$questionno = 1;
$numberlimit = $select_faqnum;
while($questionno<=$numberlimit)
{
echo $questionno;
$questionno++;
}
?>
But i doesn't know how to display the question number before the question by combining both the codes. I need the output should display the question with question number. How can i do that?
Am I missing something? I am not sure why you would make it so complex.
Since your recordset is already determining the number of rows, why not just do this:
if($selectfaq_result > 0)
{
//initialise your variable
$question_number = 0;
while($fetch_faq = mysql_fetch_array($selectfaq_result))
{
//increment your variable
$question_number++;
$faqid = $fetch_faq['intFaqid'];
$fquestion = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varQuestion']))));
$fanswer = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varAnswer']))));
?>
//concatenate the string to include the variable.
//Don't forget to leave a space after it so it looks pretty
<h3><?php echo $question_number . ": " . $fquestion; ?></h3>
<p><?php echo $fanswer; ?></p>
<?php
}
Your line number will finish when you run out of records
<?php
$select_faq = "Select `intFaqid`, `varQuestion`,`varAnswer` FROM `tbl_faq`";
$selectfaq_result = mysql_query($select_faq);
$select_faqnum = mysql_num_rows($selectfaq_result);
if($select_faqnum > 0)
{
$question_number = 0;
while($fetch_faq = mysql_fetch_array($selectfaq_result))
{
$question_number++;
$faqid = $fetch_faq['intFaqid'];
$fquestion = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varQuestion']))));
$fanswer = strip_tags(ucfirst(stripslashes(nl2br($fetch_faq['varAnswer']))));
?>
<h3><?php echo "$question_number. $fquestion"; ?></h3>
<p><?php echo $fanswer; ?></p>
<?php
}
}
?>
is that what you are looking for ?

Categories