If statement not working in my conditional ternary operator - php

I have the following if statement in PHP:
<?php
for ($i = 1; $i <= 10; $i++) {
echo "<option " . $carDoors == $i ? "selected = 'selected'" : "" . " >" . $i ."</option>";
}
?>
I need the selectlist to be based on the value of $carDoors and if that's the case, I want to echo selected = 'selected'. At the moment I keep getting a fully empty selectbox. What am I doing wrong?

The problem of your code is, that the ternary operator ?: has a higher precedence than the concatenation operator .. Your code is therefore evaluated as:
if ($carDoors == $i) {
echo "<option selected = 'selected'";
} else {
echo "<option >" . $i ."</option>";
}
To get your desired output you should use brackets arround your short if:
echo "<option " . ($carDoors == $i ? "selected = 'selected'" : "") . " >" . $i ."</option>";
A list of operator precedence can be found in the official PHP documentation.

You can use ? by this way:
<?php
for ($i = 1; $i <= 10; $i++) {
$selected = $carDoors == $i ? "selected = 'selected'" : "";
echo "<option " . $selected . " >" . $i ."</option>";
}
?>
or simple insert it into ():
for ($i = 1; $i <= 10; $i++) {
echo "<option " . ($carDoors == $i ? "selected = 'selected'" : "") . " >" . $i ."</option>";
}

Related

How to retain the value of Select Option inside a For Loop using PHP

I have a working code below. Basically, the code prints the options 50 times and 4 is the default selected option.
for ($i = 1; $i <= 50; $i++) {
if($i == 4){
echo '<option value="' . $i . '" selected>' . $i . '%</option>';
}else {
echo '<option value="' . $i . '">' . $i . '%</option>';
}
}
but every time i click the submit button, the option field resets back to the selected option even though the variables was captured properly.
It would be good if the option selected by the user is preserved after the button was clicked and the only time it reset back to the selected defaults is if the page was refreshed.
check if the value is sent by post if not assign 4 to the variable option
<form action="#" method="post" accept-charset="utf-8">
<select name="select">
<?php
if(isset($_POST['select']))
{
$option= $_POST['select'];
}
else
$option=4;
for ($i = 1; $i <= 50; $i++) {
if($i == $option){
echo '<option value="' . $i . '" selected>' . $i . '%</option>';
}else {
echo '<option value="' . $i . '">' . $i . '%</option>';
}
}
?>
</select>
<input type="submit" name="" value="Sumbit">
</form>
This should do it - it uses the value sent from the client if it exists, or 4 if not.
if (isset($_POST['selected_value'])) {
$selected = $_POST['selected_value'];
} else {
$selected = 4;
}
for ($i = 1; $i <= 50; $i++) {
if($i == $selected){
echo '<option value="' . $i . '" selected>' . $i . '%</option>';
}else {
echo '<option value="' . $i . '">' . $i . '%</option>';
}
}
Take value from posted field, say "select", if exist then take it as selected otherwise your default value.
Using below code:
$selected = (isset($_POST['select']) ? $_POST['select'] : 4);
for ($i = 1; $i <= 50; $i++) {
if($i == $selected){
echo '<option value="' . $i . '" selected>' . $i . '%</option>';
}else {
echo '<option value="' . $i . '">' . $i . '%</option>';
}
}

PHP Comparing 0 does not work

I'm trying to set a checkbox as checked in php based on an hour fields from a comma separated value string. It works well for 1-23 but for some reason hour 0 always displays as checked:
<?php
myhours = explode(",", substr($arruser['arhours'],0,strlen($arruser['arhours']) - 1));
$checked = "";
for($hour = 0; $hour <= 23; $hour++) {
if(count($myhours) > 0) {
for($h = 0; $h <= count($myhours); $h++) {
if((int)$hour == (int)$myhours[$h]) {
$checked = " checked ";
break;
}
}
} else {
$checked = "";
}
if(strlen($hour) == 1) {
echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">0$hour:00</td>";
} else {
echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">$hour:00</td>";
}
$checked = "";
}
?>
The problem is straightforward; look at the outer loop:
for ($hour = 0; $hour <= 23; $hour++) {
Consider only the first iteration, so $hour is int(0). Further in the code:
if(count($myhours) > 0) {
for($h = 0; $h <= count($myhours); $h++) {
Pay close attention to the loop condition:
$h <= count($myhours)
Consider the last iteration of that loop, so $h equals the size of your array.
if ((int)$hour == (int)$myhours[$h]) {
At this point $myhours[$h] is undefined because the array index is out of bounds (and a notice would have been emitted) and so (int)$myhours[$h] becomes (int)null which is int(0). The comparison is therefore always true when $hour has the value of int(0).
The solution is to change the loop condition to:
$h < count($myhours)
Not exactly and answer, but your code could be reduced to this:
$myhours = array(0, 10, 13, 20);
for($hour = 0; $hour <= 23; $hour++) {
echo '<td><input type="checkbox"' . ( in_array($hour, $myhours) ? ' checked' : '' ) . ' value="' . $hour . '" onchange="updatehour(' . $_REQUEST['user'] . ', this.checked, ' . $hour . ')">' . str_pad($hour, 2, '0', STR_PAD_LEFT) . ':00</td>';
}
No need for a second loop and more variables here. Also be aware to not output values from $_REQUEST directly without any check.
Demo
Try before buy
Problem solved. It was actually the count($myhours) that was causing the problem. Basically even with an empty string it still returns an array with 1 element. Changed to check if count($myhours) > 1 and everything is working as expected:
<?php
$myhours = explode(",", substr($arruser['arhours'],0,strlen($arruser['arhours']) - 1));
$checked = "";
for($hour = 0; $hour <= 23; $hour++) {
if(count($myhours) > 1) {
for($h = 0; $h <= count($myhours); $h++) {
if((int)$hour == (int)$myhours[$h]) {
$checked = " checked ";
break;
}
}
} else {
$checked = "";
}
if(strlen($hour) == 1) {
echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">0$hour:00</td>";
} else {
echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">$hour:00</td>";
}
$checked = "";
}
?>

a simple modification of a for loop

I have a simple php script that counts the number of pages in a manga script :
$omv_pager = "";
$omv_pager .= "<div class=\"well\">\n";
$omv_pager .= "<span>Manga <select class=\"form-control\" style='margin-bottom:10px;' name=\"manga\" onchange=\"change_manga(this.value)\">";
$omv_pager .= "<option class=\"form-control\" value=\"0\">Selecione Título do Manga...</option>";
for ($i = 0; $i < count($mangas); $i++) {
$m = $mangas[$i];
$omv_pager .= "<option value=\"" . omv_encode($m) . "\"" . (($m == $manga) ? " selected=\"selected\"" : "") . ">" . $m . "</option>";
}
$omv_pager .= "</select></span>\n";
if ($manga) {
if ($chapter) {
$omv_pager .= "<span>Chapter <select name=\"chapter\" onchange=\"change_chapter('$manga_escaped', this.value)\">";
for ($i = 0; $i < count($chapters); $i++) {
$cnumber = $chapters[$i]["number"];
$omv_pager .= "<option value=\"" . omv_encode($cnumber) . "\"" . (($cnumber == $chapter_number) ? " selected=\"selected\"" : "") . ">" . $cnumber . (isset($chapters[$i]["title"]) ? (" - " . $chapters[$i]["title"]) : "") . "</option>";
}
$omv_pager .= "</select></span>\n";
if ($page) {
$prevhtml = "";
if ($page <= 1) {
$prevhtml = "<img src=\"http://www.leitor.tk/themes/default/no-previous.png\" alt=\"\" />";
} else {
$prevhtml = "<img src=\"http://www.leitor.tk/themes/default/previous.png\" alt=\"Previous Page\" title=\"Previous Page\" />";
}
$nexthtml = "";
if ($page >= count($pages)) {
$nexthtml = "<img src=\"http://www.leitor.tk/themes/default/no-next.png\" alt=\"\" />";
} else {
$nexthtml = "<img src=\"http://www.leitor.tk/themes/default/next.png\" alt=\"Next Page\" title=\"Next Page\" />";
}
$omv_pager .= "<span>$prevhtml Page <select name=\"page\" onchange=\"change_page('$manga_escaped', '$chapter_number_escaped', this.value)\">";
for ($p = 1; $p <= count($pages); $p++) {
$omv_pager .= "<option value=\"" . $p . "\"" . (($p == $page) ? " selected=\"selected\"" : "") . ">" . $p . "</option>";
}
$omv_pager .= "</select> of " . count($pages) . " $nexthtml</span>\n";
}
}
}
$omv_pager .= "</div>\n";
echo $omv_pager;
What I want to do is, in the last page change the name of the to "end"
e.g : 1-2-3-4-5-6-7-8-9-10-11-12-end
And thanks to all of you guys.
Try with:
">" . ($p == count($pages) ? "end" : $p) . "</option>"
instead of
">" . $p . "</option>"
For optimization reasons you might want to buffer count($pages) into a variable before the for.

Pagination issue when working with filters

I have a pagination class with buildTrail function to display pages number.
For searching the db, this class is working great.
If i'm searching for "intel", the second page link will be "http://localhost/search/intel/pg/2".
The problem occures when i try to filter the results .EX: "http://localhost/search/intel/type/ssd" so the links for paging will display : ex"http://localhost/search/intel/type/ssd/intel/type/ssd/pg/2"
function buildTrail($param = ""){
// $cur_page = basename($_SERVER['PHP_SELF']);
$link = $_SERVER['REQUEST_URI'];
$link_array = explode('/', $link);
//$count = count($link_array);
$pagename = $link_array[1];
// echo $magename;
if(is_array($param)){
foreach($param as $a => $b){
if($a != "page"){
$url .= $pagename."/".$b;
}
}
} else {
$url = $param;
}
$trail = "";
if($this->getPages() > 1){
if($this->getFrom() > 1){
$trail .= "<a href='" . WEBSITE . "/". $url . "/pg/" . $this->getPrevious()."'>«</a>\n ";
}
if($this->getFrom() < 10 && $this->getPages() > 10){
for ($i = 1; $i <= 10; $i++){
$trail .= "<a class='". ($i == $this->getFrom() ? "selected" : "links") . "' href='" . WEBSITE . "/".$url."/pg/" . $i ."'>" . $i . "</a>\n ";
}
} elseif($this->getFrom() < 10 && $this->getPages() < 10){
for ($i = 1; $i <= $this->getPages(); $i++){
$trail .= "<a class='". ($i == $this->getFrom() ? "selected" : "links") . "' href='" . WEBSITE . "/".$url."/pg/" . $i ."'>" . $i . "</a>\n ";
}
}elseif ($this->getFrom() >= 10 && $this->getFrom() <= ($this->getPages() - 5) ){
for ($i = ($this->getFrom() - 5); $i <= ($this->getFrom() + 5); $i ++){
$trail .= "<a class='". ($i == $this->getFrom() ? "selected" : "links") . "' href='" . WEBSITE . "/".$url."/pg/" . $i ."'>" . $i . "</a>\n ";
}
} else {
for ($i = ($this->getPages() - 10); $i <= $this->getPages(); $i ++){
$trail .= "<a class='". ($i == $this->getFrom() ? "selected" : "links") . "' href='" . WEBSITE . "/".$url."/pg/" . $i ."'>" . $i . "</a>\n ";
}
}
if($this->getFrom() < $this->getPages()){
$trail .= "<a href='" . WEBSITE . "/".$url."/pg/" . $this->getNext()."'>»</a>\n ";
}
}
return $trail;
}
Solved with htaccess
RewriteEngine On
Options -Indexes
Options +FollowSymLinks
<Files .htaccess>
deny from all
</Files>
RewriteRule ^search/(.*)/pg/([0-9]+)(/)?$ search.php?page=$2&q=$1 [NC,L]
RewriteRule ^search/(.*)/sort/(.*)/$ search.php?q=$1&sort=$2 [NC,L]
RewriteRule ^search/(.*)/sort/(.*)$ search.php?q=$1&sort=$2 [NC,L]

Add "selected" in a <select> based on value from database

how do I select the correct value in a when I get the value from a database on page load?
I have this code now, but when it runs it gives the attribute "selected" to every number after the given number from the database.
<?php
$i = 8;
while ( $i <=24 ) {
if ($i == $store_info['weekdays_open_time']) {
$selected = " selected";
}
print ("<option value='" . $i ."'" . $selected . ">" . $i . "</option>");
$i++;
}
?>
Change you code to:
<?php $i = 8; while ( $i <=24 ) {
$selected = ($i == $store_info['weekdays_open_time'])?" selected" : "";
print ("<option value='" . $i ."'" . $selected . ">" . $i . "</option>");
$i++;
} ?>
You need to reset the $selected variable inside the while loop:
<?php
$i = 8;
while ($i <= 24) {
$selected = '';
if ($i == $store_info['weekdays_open_time]) $selected = ' selected="selected"';
print ("<option value='" . $i ."'" . $selected . ">" . $i . "</option>");
$i++;
}
?>
Edit: Make sure you always set a value for each variable you use; it's a good habit. In your code you used the variable selected inside the print function, without always having a variable value assignment first.
you never clear your $selected variable, basically once it finds a correct answer, $selected is set to " selected" and is no longer an empty variable, so each iteration when you call for it, it prints " selected" not "";
<?php
$i = 8;
while ( $i <=24 ) {
$selected = ( $i == $store_info['weekdays_open_time']) ? " selected='selected'" : "";
print ("<option value='" . $i ."'" . ( () ? )$selected . ">" . $i . "</option>");
$i++;
} ?>
You could just replace the whole if statement :
<?php
$i = 8;
while ( $i <= 24 ) {
echo "<option value='" . $i ."'" ;
echo ($i == $store_info['weekdays_open_time'] ? ' selected' : '');
echo ">" . $i . "</option>";
++$i;
}
Check it :
<?php
$i = 8;
while ($i <= 24) {
?>
<option value="<?PHP echo $i; ?>" <?PHP if ($i == $store_info['weekdays_open_time']) { echo "selected='selected'";} ?> > <?PHP echo $i; ?></option>
<?
$i++;
}
?>
Hope it will definitely work :)
You may simply use
$i = 8;
while ( $i <=24 ) {
$selected = $i == $store_info['weekdays_open_time'] ? 'selected' : '';
echo "<option value='$i' $selected>$i</option>";
$i++;
}
Also, it's not necessary to use . when you have variables inside "double quotes" and it's better to use echo instead of print because echo is a language construct and it's faster than print function.
An Example.

Categories