How to write a loop that generates range intervals in PHP? - php

I'm newbie here. I want to ask about for loops in PHP.
How to write code that will output this:
i =1;
j = 0-20;
then if i=2; j = 20-40,
i=3; j=40-60,
and so on.
Notes: j is range data from 0-(+20);
I have no idea how to start.

i = 1; range = 0-20;
i = 2; range = 20-40;
i = 3; range = 40-60;
...
You wrote the pattern yourself: "range data from 0-(+20)". You have 3 variables there, i and range defined by min and max. You need to take some time thinking how each of these will change based on how i will change. Then it shouldn't be hard to come up with something like this:
$rangeSize = 20;
for ($i = 0; $i < 10; ++$i) {
$rangeMin = $i * $rangeSize;
$rangeMax = $rangeMin + $rangeSize;
echo "$i : $rangeMin - $rangeMax" . PHP_EOL;
}
output:
0 : 0 - 20
1 : 20 - 40
2 : 40 - 60
3 : 60 - 80
4 : 80 - 100
5 : 100 - 120
6 : 120 - 140
7 : 140 - 160
8 : 160 - 180
9 : 180 - 200

Should be something along those lines
refer to http://www.w3schools.com/php/php_looping_for.asp for the official documentation
<?php
$max_i = put the maximum value for i here
for ($i = 0; $i <= $max_i; $i++)
{
echo "i = $i <br>";
echo "j = $i*20 - 20 <br>";
}
?>

Related

PHP: for loop $i value turns zero if the number is greater

I want to turn the $i variable value to start counting from 1 if the given value is greater than 10:
here is what i am trying to achieve
<?php
$givenValue = 15; //number of x value
for ($i = 1; $i < $givenValue; $i++) {
if ($givenValue > 10){
$i = 1;
}
echo $i."<br>";
}
?>
This is how i want my result to look like
output: 1
output: 2
output: 3
output: 4
output: 5
output: 6
output: 7
output: 8
output: 9
output: 10
output: 1
output: 2
output: 3
output: 4
output: 5
in for loop body
Any help is welcome
You can use modulo calculation to get the result you want.
I also changed your if from $givenvalue to $i as $givenvalue will "always" be 10+.
$givenValue = 15; //number of x value
for ($i = 1; $i <= $givenValue; $i++) {
if ($i > 10){
Echo $i%10 . "\n";
}else{
echo $i . "\n";
}
}
https://3v4l.org/5afc5
Another option, if that is possible for you, is to start at zero and only use modulo calculation and add one to it to get the same result.
This also means I need to stop the loop at <$givenvalue as your original code shows.
$givenValue = 15; //number of x value
for ($i = 0; $i < $givenValue; $i++) {
Echo $i%10+1 . "\n";
}
https://3v4l.org/r0sgA
A method that uses less looping is to add 10 to the loop on each iteration and create the values using range().
Then add them to the array with array_merge, and output with implode.
$givenValue = 47; //number of x value
$breakpoint = 10;
$arr=[];
For($i = $breakpoint; $i< $givenValue;){
// Add new values from 1-$breakpoint in array
$arr = array_merge($arr, range(1,$breakpoint));
$i +=$breakpoint;
}
// Loop will exit before all values been collected
// Add the rest of the values
$arr = array_merge($arr, range(1,$givenValue-($i-10)));
// Echo the values in array
Echo implode("\n", $arr);
https://3v4l.org/jGsO4
Your code can be written like this:
<?php
$givenValue = 15; //number of x value
for ($i = 1; $i <= $givenValue; $i++)
{
if ($i > 10)
{
$i = 1;
$givenValue-=10;
}
echo "output: $i\n";
}
?>
http://sandbox.onlinephpfunctions.com/code/ed34d8dcd12a9a5a866b73338ad1209f55298519
You are resenting the counter, I would expect the behaviour you have. To do what you want add another counter to the mix
$j=1;
$givenValue = 15; //number of x value
for ($i = 1; $i <= $givenValue; $i++) {
if ($j > 10){
$j = 1;
}
echo $j."\n";
++$j;
}
You also had several missing ;
Output:
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
If you want to end on 5 you have to do 16 as the $givenValue or change it to <= less than or equal
See it here live
See what I have now, the $i variable counts to the $givenValue then the $j variable counts along side it, but with a range of 1-10 ( resets to 1 after 10 )

PHP if else with modulo number

I have number from 1 until 200, number will be printed in a page, each page has a limit by 81. When reach 81 then print into the next page.
This is output i want:
number = 200;
print number 1 - 81 in page 1
create new page
print number 82 - 162 in page 2
create new page
print number 163 - 200 in page 3
How to do it in PHP?
Update:
I mean i just want to print like above. No need of size of paper.
Here's what i have done
$number = 200;
$limit = 81;
$page = ceil($number/$limit);
for($i = 0; $i < $page; $i++){
echo "print number 1 - ". 200-81 ." in page".$i; // i'm stuck in here
}
I think this might work:
$number = 200;
$limit = 81;
$page = ceil($number/$limit);
for($i = 0; $i < $page; $i++){
$start = $i*$limit+1;
$last = ((($i+1)*$limit));
$last = $last>$number?$number:$last;
echo "<br>print number $start - $last in page".($i+1);
}

Simple PHP program requires less time to execute

i had applied for a job recently and the requirement was to complete a test and then interview
2 questions were given for test which was very simple and i did it successfully but still i was told that i have failed the test because the script took more than 18 seconds to complete execution. here is the program i dont understand what else i could do to make it fast. although i have failed the test but still wants to know else i could do?
Program language is PHP and i had to do it using command line input
here is the question:
K Difference
Given N numbers , [N<=10^5] we need to count the total pairs of numbers that have a difference of K. [K>0 and K<1e9]
Input Format:
1st line contains N & K (integers).
2nd line contains N numbers of the set. All the N numbers are assured to be distinct.
Output Format:
One integer saying the no of pairs of numbers that have a diff K.
Sample Input #00:
5 2
1 5 3 4 2
Sample Output #00:3
Sample Input #01:
10 1
363374326 364147530 61825163 1073065718 1281246024 1399469912 428047635 491595254 879792181 1069262793
Sample Output #01:
0
Note: Java/C# code should be in a class named "Solution"
Read input from STDIN and write output to STDOUT.
and this is the solution
$fr = fopen("php://stdin", "r");
$fw = fopen("php://stdout", "w");
fscanf($fr, "%d", $total_nums);
fscanf($fr, "%d", $diff);
$ary_nums = array();
for ($i = 0; $i < $total_nums; $i++) {
fscanf($fr, "%d", $ary_nums[$i]);
}
$count = 0;
sort($ary_nums);
for ($i = $total_nums - 1; $i > 0; $i--) {
for ($j = $i - 1; $j >= 0; $j--) {
if ($ary_nums[$i] - $ary_nums[$j] == $diff) {
$count++;
$j = 0;
}
}
}
fprintf($fw, "%d", $count);
Your algorithm's runtime is O(N^2) that is approximately 10^5 * 10^5 = 10^10. With some basic observation it can be reduced to O(NlgN) which is approximately 10^5*16 = 1.6*10^6 only.
Algorithm:
Sort the array ary_nums.
for every i'th integer of the array, make a binary search to find if ary_nums[i]-K, is present in the array or not. If present increase result, skip i'th integer otherwise.
sort($ary_nums);
for ($i = $total_nums - 1; $i > 0; $i--) {
$hi = $i-1;
$low = 0;
while($hi>=$low){
$mid = ($hi+$low)/2;
if($ary_nums[$mid]==$ary_nums[$i]-$diff){
$count++;
break;
}
if($ary_nums[$mid]<$ary_nums[$i]-$diff){
$low = $mid+1;
}
else{
$hi = $mid-1;
}
}
}
}
I got the same question for my technical interview. I wonder if we are interviewing for the same company. :)
Anyway, here is my answer I came up with (after the interview):
// Insert code to get the input here
$count = 0;
sort ($arr);
for ($i = 0, $max = $N - 1; $i < $max; $i++)
{
$lower_limit = $i + 1;
$upper_limit = $max;
while ($lower_limit <= $upper_limit)
{
$midpoint = ceil (($lower_limit + $upper_limit) / 2);
$diff = $arr[$midpoint] - $arr[$i];
if ($diff == $K)
{
// Found it. Increment the count and break the inner loop.
$count++;
$lower_limit = $upper_limit + 1;
}
elseif ($diff < $K)
{
// Search to the right of midpoint
$lower_limit = $midpoint + 1;
}
else
{
// Search to the left of midpoint
$upper_limit = $midpoint - 1;
}
}
}
#Fallen: Your code failed for the following inputs:
Enter the numbers N and K: 10 3
Enter numbers for the set: 1 2 3 4 5 6 7 8 9 10
Result: 6
I think it has to do with your calculation of $mid (not accounting for odd number)

Add Ellipsis in PHP Pagination

.
//Prev
.
for($number = 1; $number <= $num_pages; $number++)
{
if($page == $number)
{
$navigator .= "<b>[$number]</b> ";
}
else
{
$navigator .= "<a href='?c=".$_SESSION['cID']".&rows=".$per_page."&page=$number'>$number</a> ";
}
}
.
//Next
.
This is the snippet that prints number of pages.
Sample output:
Previous 1 2 3 4 [5] 6 7 8 9 10 Next
5 is the current page.
Problem: page numbers are shown in sequence with no restrictions. If i have 100 pages, all numbers show up.
Question: I need my paging numbers appear as the following...
Assume we only have 7 ($num_pages) pages:
Previous 1 2 [3] 4 5 6 7 Next
Assume we have 90 pages:
[1] 2 3 4 5 6 7 ... 90 Next
Assume user clicked the 7th page:
Previous 1 ... 5 6 [7] 8 9 10 11 ... 90 Next
Assume user clicked 11th page:
Previous 1 ... 9 10 [11] 12 13 14 15 ... 90 Next
Assume user clicked 15th page:
Previous 1 ... 13 14 [15] 16 17 18 19 ... 90 Next
Assume user clicked 90th page:
Previous 1 ... 84 85 86 87 88 89 [90]
Any help will be appreciated.
$radius = 3;
for($i = 1; $i <= $total; $i++){
if(($i >= 1 && $i <= $radius) || ($i > $current - $radius && $i < $current + $radius) || ($i <= $total && $i > $total - $radius)){
if($i == $current) echo "<b>".$i."</b>";
}
elseif($i == $current - $radius || $i == $current + $radius) {
echo "... ";
}
}
This should be more than enough to get you started at least
$count = 7; // number to show
// start at half threshold down from the current location.
$number = $current - round($count/2);
if( $number > 1 ) echo '...';
else $ // increase to have number start at 1.
for( $number; $number < $number + $count; $number++)
{
// your for loop as normal
}
if( $number < $total ) echo '...';
An elegant solution for this kind of thing is to use "logarithmic page navigation". See my answer to this question (PHP code included):
How to do page navigation for many, many pages? Logarithmic page navigation

stuck at displaying a PHP paginator

I'm trying to create a paginator. I have created a paginator class with properties you can see below. But now I'm trying to display the paginator, but I'm completely stuck on different loops (perhaps I should just go to bed :P) and stuff.
The important properties are:
windows_size // the amount of pages visible
num_pages // the total number of pages
current_page // the currently selected page
I have the following object:
o: (Paginator)
->item_count : 295
page_size : 50
window_size : 5
num_pages : 10
current_page: 1
first_index : 50
And I want to display:
[1] 2 3 4 5 ...
Or I have:
o: (Paginator)
->item_count : 295
page_size : 50
window_size : 5
num_pages : 10
current_page: 5
first_index : 50
... 3 4 [5] 6 7...
Or I have:
o: (Paginator)
->item_count : 295
page_size : 50
window_size : 5
num_pages : 10
current_page: 9
first_index : 50
... 6 7 8 [9] 10
How would I get this to be displayed?
END RESULTS (many thanks to: Wh1T3h4Ck5!)
http://pastebin.com/2KzL1Tn6
Generally, it's very simple piece of code.
You can use something like this.
function myPaginator($total_items, $items_per_page, $visible_pages_pad, $active_page) {
$res = '';
if ($items_per_page > 0 && $active_page > 0 && $visible_pages_pad) {
$max_page = floor($total_items/$items_per_page);
if ($total_items % $items_per_page > 0) $max_page++;
if ($active_page <= $max_page) {
$visible_pages = $visible_pages_pad * 2 + 1;
if ($max_page <= $visible_pages) {
$minp = 1;
$maxp = $max_page;
}
else {
$minp = $active_page - $visible_pages_pad;
if ($minp < 1) $minp = 1;
$maxp = $minp + $visible_pages - 1;
if ($maxp > $max_page) {
$maxp = $max_page;
$minp = $maxp - $visible_pages + 1;
}
}
for ($i = $minp; $i <= $maxp; $i++) {
$page = $i == $active_page ? "[$i]" : $i; // create links here
$res .= "$page ";
}
$res = trim($res);
if ($minp > 1) $res = '... ' . $res; // left dots
if ($maxp < $max_page) $res .= ' ...'; // right dots
}
}
return $res == '' ? false : $res;
}
Parameters:
$total_items - total number of items in list
$items_per_page - how menu items you want on page
$visible_pages_pad - left/right padding (this value * 2 + 1 = number of paginator items)
$active_page - selected page in paginator
Result:
Function myPaginator() returns
false if something is wrong, otherwise returns string.
Limitations:
all parameters should be integers
$items_per_page > 0
$visible_pages_pad > 0
1 <= $active_page <= {TOTAL NUMBER OF PAGES}
Usage:
$total_items = 250; // total items
$items_per_page = 20; // 250/20 = 13 pages
$visible_pages_pad = 2; // 5 pages visible in paginator (2*2+1)
$active_page = 1;
echo myPaginator($total_items,$items_per_page,$visible_pages_pad,$active_page);
// output: [1] 2 3 4 5 ...
$active_page = 2;
echo myPaginator($total_items,$items_per_page,$visible_pages_pad,$active_page);
// output: 1 [2] 3 4 5 ...
$active_page = 3;
echo myPaginator($total_items,$items_per_page,$visible_pages_pad,$active_page);
// output: 1 2 [3] 4 5 ...
$active_page = 6;
echo myPaginator($total_items,$items_per_page,$visible_pages_pad,$active_page);
// output: ... 4 5 [6] 7 8 ...
$active_page = 11;
echo myPaginator($total_items,$items_per_page,$visible_pages_pad,$active_page);
// output: ... 9 10 [11] 12 13
$active_page = 12;
echo myPaginator($total_items,$items_per_page,$visible_pages_pad,$active_page);
// output: ... 9 10 11 [12] 13
$active_page = 13;
echo myPaginator($total_items,$items_per_page,$visible_pages_pad,$active_page);
// output: ... 9 10 11 12 [13]
Note: $visible_pages_pad is number of pages in paginator left/right of the active-page number.
Hope this helps...

Categories