I need a little help with an if statement in php. I'm trying to set a variable called offset according to a page that I am loading in WordPress. Here's the variable:
$offset = ($paged * 6);
What it does is it loads the first page, which is:
http://example.com/blog
and $offset is thus set to 0 because $paged is referring to the appending number on the URL. The second page, for example is:
http://example.com/blog/2/
which makes $offset set to 12. The problem is, I need the second page to define $offset as 6, the third page to define $offset as 12, etc. I tried using:
$offset = ($paged * 6 - 6)
which works except on the first page. On the first page it defines $offset as -6. SO, I wanted to create an if statement that says if $paged is equal to 0 then $offset is equal to 0, else $offset is equal to ($paged * 6 - 6).
I struggle with syntax, even though I understand what needs to be done here. Any help would be greatly appreciated. Thanks!
Because this is two different cases which cannot be easily integrated into a single formula, use an if statement:
if ($paged == 0)
$offset = 0;
else
$offset = ($paged - 1) * 6;
You can write this shorter using the ternary operator, but I think the above if statement is more readable:
$offset = ($paged == 0) ? 0 : ($paged - 1) * 6;
An alternative:
if($paged == 0) $paged = 1;
$offset = ($paged - 1) * 6;
or
$offset = ($paged) ? ($paged - 1) * 6 : 0;
you can use the following one line code
$offset = max(($paged - 1) * 6, 0);
You could use: $offset = max(0, $paged * 6 -6);. Which takes the maximum of 0 and the other value. If the other value is negative, then 0 will be the result.
Now, to use an if statement, this is how you would do it:
$offset = $paged * 6 - 6;
if ($offset < 0) {
$offset = 0;
}
Or:
if ($paged == 0) {
$offset = 0;
} else {
$offset = $paged * 6 - 6;
}
And you might want to use a ternary operator for this simple case:
$offset = ($paged == 0)? 0: ($paged * 6 - 6);
(which does the exact same thing as the above)
Note: You could replace 6*a-6 = 6*(a-1), but it's of no importance in the code, just readability...
Related
I am trying to familarise myself with for loop as I only understand the basics.
I am trying to simplify the code below
$round1 = $max / 2;
$round2 = $round1 + ($max / 2 / 2);
$round3 = $round2 + ($max / 2 / 2 / 2);
$round4 = $round3 + ($max / 2 / 2 / 2 / 2);
$round5 ...
With this:-
$round = array($max/2);
for ($i=1;$i<$max;$i++) {
$round[] = $round[$i -1] + $max/pow(2, $i + 1);
}
And now for the next code:-
if($matchno <= $round[0]) {
$scores_round1.= '['.$score1.', '.$score2.'],';
}
if($matchno > $round[0] AND $matchno <= $round[1]) {
$scores_round2.= '['.$score1.', '.$score2.'],';
}
if($matchno > $round[1] AND $matchno <= $round[2]) {
$scores_round3.= '['.$score1.', '.$score2.'],';
}
if($matchno > $round[2] AND $matchno <= $round[3]) {
$scores_round4.= '['.$score1.', '.$score2.'],';
}
Can the above be used in a for loop to avoid using if() ?
Thanks for help
You can check for round1 and for the rest:
for ($i=1;$i<$max;$i++) {
if($matchno>$round[$i] AND $matchno <= $round[$i+1])
${'scores_round'.$i}.='['.$score1.', '.$score2.'],';
}
for($i=0;$i< count($round); $i++){
if($match < $round[$i]){
${"scores_round".$i}.= '['.$score1.', '.$score2.'],';
break;
}
}
By watching the if statements, we notice some things:
First of all, there is no *else if* statement. That means that all if statement checks must be executed.
Additionally, there is a check whether the $matchno is less than $round[0], without any check for greater than in this if statement (the first one).
Another point is that $scores_roundX starts with X=1 and not 0.
Obviously, you will have to use one if inside the loop.
So, we are going to form loop code making some small tricks:
for($i = -1; $i < count($round)-1 ; ++$i){
if(($i = -1 OR $matchno > $round[$i]) AND ($matchno <= $round[$i+1])){
${"scores_round".$i+2} .= '['.$score1.', '.$score2.'],';
}
}
We will initialize THE $i with -1, to use it for the first statement execution.
We will put as for statement the $ to be less than the count of the
array minus 1 (because we index using $i+1 in our if statement,
inside the loop).
We will perform greater than check only if the $i is not -1, and this
will happen on the second check (second if in initial code). Here, we also use
the partial evaluation feature of the language, and that means that in the OR sub-statement,
if the first part comes as true, the second one is not ecaluated.
We will make $i+2 at the $scores_round forming, because we start from
-1 on our for loop.
I am trying to limit the shown pagination. My site has 500+ pages, and all 500+ numbers are shown in the pagination.
I am trying to limit it like this:
Prev 1 2 3 4 5 6 Next
My code:
$skin = new skin('site/pagination'); $pagination = '';
if ($pages >= 1 && $page <= $pages) {
for ($x=1; $x<=$pages; $x++) {
$TMPL['pagination'] = ($x == $page) ? '<strong>'.$x.'</strong> ' : ''.$x.' ';
$pagination .= $skin->make();
}
}
pagination page number limit problem solve by chnage
for ($x=1; $x<=$pages; $x++)
to
for($x = max(1, $page - 5); $x <= min($page + 5, $pages); $x++)
What do you expect this to do?:
for ($x=1; $x<=$pages; $x++)
It is going to create an entry for every page. If you don't want that, limit it how it makes sense:
for ($x=1; $x <= min(5, $pages); $x++)
Even better would be to consider the current page:
for ($x=max($curpage-5, 1); $x<=max(1, min($pages,$curpage+5)); $x++)
//Let's say you want 3 pages on either side of your current page:
$skin = new skin('site/pagination'); $pagination = '';
$currentPage = get the current page number however you have it stored;
// set the lower bound as 3 from the current page
$fromPage = $currentPage - 3;
// bounds check that you're not calling for 0 or negative number pages
if($fromPage < 1) {
$fromPage = 1;
}
// set the upper bound for what you want
$toPage = $fromPage + 7; // 7 is how many pages you'd like shown
// check that it doesn't exceed the maximum number of pages you have
if($toPage > $maxPages) {
$toPage = $maxPages;
}
// iterate over your range
for ($x=$fromPage; $x<=$toPage; $x++) {
$TMPL['pagination'] = ($x == $page) ? '<strong>'.$x.'</strong> ' : ''.$x.' ';
$pagination .= $skin->make();
}
For large numbers of pages, consider displaying links using "logarithmic" pagination. See my answer here (PHP code included):
How to do page navigation for many, many pages? Logarithmic page navigation
I tried the answers provided by wallyk and Hemang but they fell short for my pagination case. Their answers would sometimes display less links than the range. I had to add some max and min statements.
Here is my take in Javascript code:
var minPage = Math.max(Math.min(currentPage - (range / 2), totalPages - range), 0);
var maxPage = Math.min(Math.max(currentPage + (range / 2), range), totalPages);
The range is the number of links always displayed.
The totalPages is the total number of pages to iterate over.
The currentPage is the currently displayed page.
Note that my pagination index is 0 based.
Am working on array pagination. I am having some trouble forming equations. what I want is when
$CurrentPage = 1 then $Start = 1,
if $CurrentPage = 2 then $Start = 30,
if $CurrentPage = 3 then $Start = 60,
if $CurrentPage = 4 then$Start = 90
and so on..
How do I write the if else block ?
you can also use this:
$Start = ($currentPage==1 ? 1 : ($currentPage-1)*30);
and forget all the if/else.
If the current page is one, display from result one (for what ever reason not from result 0), if page bigger than one display from result (page - 1)*30
if ((int)$currentPage > 1) {
$start = ($currentPage - 1)*30;
}
else {
$start = 1;
}
or in a shorter way
$start = ($currentPage > 1) ? ((int)$currentPage - 1) * 30 : 1;
Keep it simple:
$Start = max(1, ($currentPage-1) * 30);
I want to make a minimalistic pagination script that basically does three things:
On first page, just a next button.
On last page, just a previous button.
For all others in between, both.
I have most of the code worked out, but I'm just making some if/elseif statements that determine which page the user is on and I'm having a bit of trouble. (those at bottom) First, here's the query code:
$per_page = 10;
$pages_query = mysql_query("SELECT COUNT(idnum) FROM images");
$pages = ceil(mysql_result($pages_query, 0) / $per_page);
$page = (isset($_GET['page'])) ? (int)$_GET['page'] :1;
$start = ($page -1) * $per_page;
$query = mysql_query("SELECT * FROM images ORDER BY idnum DESC LIMIT $start, $per_page");
And here's the if statement part:
$nextend = $pages - 1;
$next = $page + 1;
$previous = $page - 1;
if ($pages >= 1 && $page = 1) {
echo 'next';
} elseif ($pages >= 1 && $page = 2) {
echo 'previous';
}
It always results in the next button, no matter what page I'm on. How do I detect the page number so I can display the pagination buttons the way I want to? By the way, I know I don't have the else statement for the middle pages (next and previous) yet.
You are assigning in your if statements rather than comparing. You don't want this in your if statement:
$page = 1
That just assigns 1 to $page.
You want this:
$page == 1
Or this:
$page === 1
$nextend = $pages - 1;
$next = $page + 1;
$previous = $page - 1;
$maxpages = ? //You need to have a variable with the last page number
if ($pages > 1) {
echo 'previous';
}
if ($page < $maxpages) {
echo 'next';
}
I don't understand what logic you are trying to do with your if/else statements, also when checking if a variable is equal to a number/other variable your "==" not "="
What you've got to do is way simple:
If you're not on the first page, you always have to show a back button.
If you're not on the last page you always have to show a next button.
Please note that both those conditions can happen at the same time so using an elseif between them won't work as it will only allow one of them to execute.
Example:
if ( $page > 1 )
{
echo( "Previous" );
}
if ( $page < $pages )
{
echo( "Next" );
}
This question already has answers here:
Stacking Multiple Ternary Operators in PHP
(11 answers)
Closed 2 years ago.
I am fairly capable at using the PHP ternary operator. However I have hit a roadblock at trying to figure out why the code below does not match the if-else equivalent structure. The test was run three times on different numbers. The output for each structure is below the code.
Ternary:
$decimal_places = ($max <= 1) ? 2 : ($max > 3) ? 0 : 1;
Ternary Output:
max: -100000 decimal: 0
max: 0.48 decimal: 0
max: 0.15 decimal: 0
If-Else
if($max <= 1)
$decimal_places = 2;
elseif($max > 3)
$decimal_places = 0;
else
$decimal_places = 1;
If-Else Output:
max: -100000 decimal: 2
max: 0.48 decimal: 2
max: 0.15 decimal: 2
Can anyone please tell me why the these two control stuctures do not output the same data?
Your right-hand-side ternary expression needs to be wrapped in parentheses so it'll be evaluated by itself as a single expression:
$decimal_places = ($max <= 1) ? 2 : (($max > 3) ? 0 : 1);
// Another way of looking at it
$decimal_places = ($max <= 1)
? 2
: (($max > 3) ? 0 : 1);
Otherwise your ternary expression is evaluated from left to right, resulting in:
$decimal_places = (($max <= 1) ? 2 : ($max > 3)) ? 0 : 1;
// Another way of looking at it
$decimal_places = (($max <= 1) ? 2 : ($max > 3))
? 0
: 1;
Which, translated to if-else, becomes this:
if ($max <= 1)
$cond = 2;
else
$cond = ($max > 3);
if ($cond)
$decimal_places = 0;
else
$decimal_places = 1;
Therefore $decimal_places ends up as 0 for all values of $max except 2, in which case it evaluates to 1.
The code is executed as
$decimal_places = (($max <= 1) ? 2 : ($max > 3)) ? 0 : 1;
so you'll never get 2 and 1 only when 1 < $max <=3. This is because the conditional operator is left-associative. Solution: Place parentheses to make sure the order you want is coded:
$decimal_places = ($max <= 1) ? 2 : (($max > 3) ? 0 : 1);
Just put the parenthesis and you would be fine, like this:
$decimal_places = ($max <= 1) ? 2 : (($max > 3) ? 0 : 1);
As others pointed out, use paranthesis.
However, if you actually want to make it readable, what about this:
$decimal_places =
($max <= 1) ? 2 : (
($max > 3) ? 0 : (
1
));
This still looks super awkward, but this awkwardness has a regular shape, so it's easier to live with.
$drink = 'wine';
return
($drink === 'wine') ? 'vinyard' : (
($drink === 'beer') ? 'brewery' : (
($drink === 'juice') ? 'apple tree' : (
($drink === 'coffee') ? 'coffeebeans' : (
'other'
))));
You could of course omit the last pair of brackets, but that would make it less regular-looking.