PHP Pagination - detect current page - php

What is the best way to detect/print the current page number (pagination)?
I tried two different ways, and now i want to know if there exists a better way to do it.
I:
$number = 12; //current page number
$all = 40; // all pages
$range = 4; // number of pages shown (up and down)
$min = $number-$range;
$max= $number+$range+1;
for($i=$min; $i<$number;$i++) {
echo "<a href='#'>$i</a><br/>";
}
echo "$number<br/>";
for($i=($number+1); $i<$max;$i++) {
echo "<a href='#'>$i</a></br>";
}
II:
$number = 12; //current page number
$all = 40; // all pages
$range = 4; // number of pages shown (up and down)
$min = $number-$range;
$max= $number+$range+1;
for($i=$min; $i<$max;$i++) {
if($i!=$number) {
echo "<a href='#'>$i</a><br/>";
} else {
echo "$i<br/>";
}
}
I also checked the speed of both solutions (using different high-number $all values) and first one is faster in most cases.
Thanks for suggestions :)

Here's a functional alternative (for 0 to 10 pages; replace it with $min $number-1 .. )
echo implode("<br/>",
array_map(function($x){
return "<a href='..'>$x</a>";
}, range(0,10))
);
Please time it, and let me know. :)

Related

How to compare 2 numeric strings

I have 2 strings like this
$s1="32.56.86.90.23";
$s2="11.25.32.90.10";
I need to compare $s1 and $s2 and find if there are 2 or more numbers in common.
I am using this way
$s1_ar=explode(".",$s1);
$s2_ar=explode(".",$s2);
$result=array_diff($s1_ar,$s2_ar);
$rt1=5-count($result);
if($result>=2){ echo "YES"; } else {echo "no"; }
Since I need millions values of $s1 and $s2 and the code above seems to be slow, do you know alternative way to execute the work faster ?
I tested it with the following code, one million times, less than 2 seconds on my 3 years old laptop.
Loop 1M times takes no time, most time is used for displaying.
Comment off the display, 1M loops, 0.816432 seconds
Saved the results into a file, ~13.564MB, 0.731708 seconds
ob_start();
$t1 = microtime();
for($i=1; $i<=1000000; $i++) {
$s1="32.56.86.90.23";
$s2="10.25.30.90.10";
$s1_ar=explode(".",$s1);
$s2_ar=explode(".",$s2);
$result=array_diff($s1_ar,$s2_ar);
$rt1=5-count($result);
if($result>=2){ echo $i . " YES<br>"; } else {echo $i . " no<br>"; }
}
$out = ob_get_contents();
ob_end_clean();
var_dump($out);
echo '<p>'.(microtime() - $t1).'</p>';
Try this.
$s1="32.56.86.90.23";
$s2="11.23.32.90.10";
$s1_ar=explode(".",$s1);
$s2_ar=explode(".",$s2);
//assuming $s1_ar and $s2_ar both has unique values if not please make them unique
$result_array = array();
$hasMatch = 0;
for($i = 0; $i < count($s1_ar) && $i < count($s2_ar); $i++){
if(!isset($result_array[$s1_ar[$i]])){
$result_array[$s1_ar[$i]] = 1;
}else{
$result_array[$s1_ar[$i]]++;
}
if(!isset($result_array[$s2_ar[$i]])){
$result_array[$s2_ar[$i]] = 1;
}else{
$result_array[$s2_ar[$i]]++;
}
}
foreach($result_array as $result){
if($result >=2) $hasMatch++;
}
if($hasMatch >= 2)
echo "YES";
else
echo "NO";
I think it will solve your purpose.
Looking at: php array_intersect() efficiency
There's mention that array_intersect_key may be more efficient. But really it would be nice to have data and versions to compare results.
$s1 = "2.3.5.7.9.11.13.17";
$s2 = "2.3.4.5.6";
$s1 = array_flip(explode('.', $s1));
$s2 = array_flip(explode('.', $s2));
echo count(array_intersect_key($s1, $s2))>=2 ? 'yes' : 'no';
Output:
yes
I thought of a way to solve this in a 2*n complexity:
We loop one list and create an associative array from it's elements (LIST c) then we loop the second list and look up if the list c contains such an index/key ( c[element] ).
This shall be very light weighted :
$commons = 0;
$s1_fliped = array_flip($s1_ar)
foreach($s2_ar as $s2_el){
if ( isset($s1_fliped[$s2_el]) ){
$commons ++;
}
if($commons >=2) break;
});

how to generate a random base64 number to power of 11

im trying to work on urls, so i need a random base64 to the power of 11 number, which changes every time you refresh the page.
Im working in php.
any help would be great,
many thanks.
not sure how to go about but maybe somthing like bellow?
function toChars($number) {
$res = base_convert($number, 10,26);
$res = strtr($res,'0123456789','qrstuvxwyz');
return $res;
}
or
$res = ('0123456789','abcdefghijklmnopqrstuvxwyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
then randomly select from that till you get a 11 digit number aka(base64 to power of 11)
and echo the number here $random_base64_number = ?
Dont worry figured it out.
function base62() {
$index = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_';
$res = '';
for ($x = 1; $x <= 11; $x++) {
$res .= $index[rand(1, strlen($index))];
}
echo "The number is: $res <br>";
}

Create a custom array in PHP

I've played around with a personal project regarding a website listing PC games by year of releasing etc. (the topic it is not so important i guess) using the following structure for the links:
http://localhost/
http://localhost/?g=15
http://localhost/?g=30
http://localhost/?g=45
Like it is seen, I've display 15 games per page. What am I working right now is displaying the above links using php in a specific manner for each page (thumbnails, links, etc.):
$arr = array("","?g=15","?g=30","?g=45","?g=60","?g=75","?g=90");
foreach ($arr as $page) {
$link = 'http://localhost/' . (string)$page;
// do stuff to each page link
}
I am very satisfied with how it goes so far but I am wondering if there is a way to create the array automatically not requiring me to manually write the string, just specify the last multiple of 15 for example. I searched the web but I haven't find something concludent or maybe I don't express myself clear enough that's why any help is more than welcomed.
echo 'http://localhost';
for ($i = 15; $i < $max; $i += 15) {
echo "http://localhost/?g=$i";
}
In practice $max is calculated by how many entries there are, which is something you usually figure out from querying a database. Hope this points you in the right direction though.
You can easily generate your array:
<?php
$arr = array('');
$max = 5;
for($i = 0; $i < $max; ++$i) {
$arr[] = '?g='.($i*15);
}
?>
Thry this and tell me if it helps
$links = array();
$links[] = 'http://localhost/';
$multiplier = 5; //the mutiplier, number of links to provide
for ($i = 1; $i < $multiplier; $i++)
{
$links[$i] = 'http://localhost/?g='.(15*$i);
// do here what you want with $links[$i]
}
print_r($links);

Run A PHP function only 30% of Time

I need help creating PHP code to echo and run a function only 30% of the time.
Currently I have code below but it doesn't seem to work.
if (mt_rand(1, 3) == 2)
{
echo '';
theFunctionIWantCalled();
}
Are you trying to echo what the function returns? That would be
if(mt_rand(1,100) <= 30)
{
echo function();
}
What you currently have echoes a blank statement, then executes a function. I also changed the random statement. Since this is only pseudo-random and not true randomness, more options will give you a better chance of hitting it 30% of the time.
If you intended to echo a blank statement, then execute a function,
if(mt_rand(1,100) <= 30)
{
echo '';
function();
}
would be correct. Once again, I've changed the if-statement to make it more evenly distributed. To help insure a more even distribution, you could even do
if(mt_rand(1,10000) <= 3000)
since we aren't dealing with true randomness here. It's entirely possible that the algorithm is choosing one number more than others. As was mentioned in the comments of this question, since the algorithm is random, it could be choosing the same number over, and over, and over again. However, in practice, having more numbers to choose from will most likely result in an even distribution. Having only 3 numbers to choose from can skew the results.
Since you are using rand you can't guarantee it will be called 30% of the time. Where you could instead use modulus which will effectively give you 1/3 of the time, not sure how important this is for you but...
$max = 27;
for($i = 1; $i < $max; $i++){
if($i % 3 == 0){
call_function_here();
}
}
Since modulus does not work with floats you can use fmod, this code should be fairly close you can substitute the total iterations and percent...
$total = 50;
$percent = 0.50;
$calls = $total * $percent;
$interval = $total / $calls;
$called = 0;
$notcalled = 0;
for($i = 0; $i <= $total; $i++){
if(fmod($i, $interval) < 1){
$called++;
echo "Called" . "\n";
}else{
$notcalled++;
echo "Not Called" . "\n";
}
}
echo "Called: " . $called . "\n";
echo "Not Called: " . $notcalled . "\n";

How set paging in PHP?

I have an 300 rows(data) each page contain 10 records I need first 10 pages then click next then display next 10 page here is my code:
<?php
$eu = ($start - 0);
$limit = 10;
$this1 = $eu + $limit;
$back = $eu - $limit;
$next = $eu + $limit;
if ($nume > $limit)
{
echo'<div class="pagination right">';
if ($back >= 0)
{
echo"<a href='$page_name?start=$back&o" . $_SESSION['clicked'] . "&p=$desc'>«</a>";
}
$i = 0;
$l = 1;
for ($i = 0; $i < $nume; $i = $i + $limit)
{
if ($i <> $eu)
{
echo"<a href='$page_name?start=$i&o=" . $_SESSION['clicked'] . "&p=$desc'>$l</a>";
}
else
{
echo "<a class='active'>$l</a>";
}
$l = $l + 1;
}
if ($this1 < $nume)
{
echo "<a href='$page_name?start=$next&o=" . $_SESSION['clicked'] . "&p=$desc'>»</a>";
}
echo '</div>';
}
echo '</div></div>';
?>
Then I will get response like this http://app.ologie.us/app/admin/Screen.png
Can any one please guide to effective paging in PHP.
Here's a tutorial on basic pagination.
http://www.phpfreaks.com/tutorial/basic-pagination
Doing it like Tim said is, according to me, mainly a bad way to do this. Read in the data needed WHEN it's needed.
You could do it with a min - max index to your array.
Consider you want to display 10 records per page:
$min = $page * 10; //Page is the current page
$max = $min + 10;
Then you just loop through the data between the min - max indexes.
for($i = $min; $i < $max; $i++) {
//Echo your data like normal
}
If you're gathering your data from MySQL, you might want to look up LIMIT.
If $limit is your page size and you add another request variable $page - representing the search result page requested by the user - you can use
$start = ($page-1)*$limit;
for($i=$start;$i < $start + $limit;$i=$i+1) {
...
}
to iterate over a "page" of the results.
But of course it does not make sense to handle paging on the level of the result view. You want to limit the number of results you get from the query.
In addition I would really consider using a PHP framework rather than coding it in the way you present in your request. Chances are your application will end up to be difficult to maintain.
You do it all client side with the DataTables plugin for jQuery. This plugin also gives you a LOT more options like sorting and searching.
http://datatables.net/
If you have a VERY large table, this probably isn't a good idea, though.

Categories