user1200640
user1200640

Reputation: 1087

get the largest number from url in php?

On my website I have my pages in this format:

www.mysite.com/45.php
www.mysite.com/81.php
www.mysite.com/58.php
www.mysite.com/415.php

I have the numbers in order. How can I get the largest number which is in this case 415 and store it in a var. I tried this:

<?php
for ($urlCheck = 1000000; ; $urlCheck--){
    if (file_exists()){
        echo "true";
        break;
        }

    }

?> 

but I am not sure how I get this thing to work.

Upvotes: 0

Views: 130

Answers (2)

r55
r55

Reputation: 26

// a url looks like: http://www.mysite.com // a path looks like: /home/vhosts/www.mysite.com/public

$path = getcwd(); // get current path (needs to be where 45.php etc is) chdir($path); // go there $files = scandir('.'); // we are looking in the current directory natsort($files); $largest = intval(end($files)); // sample value: "415" $filename = end($files); // if you just want the number from a filename: $number=preg_replace('/[^\d]/','',$filename);

Upvotes: 1

Jon
Jon

Reputation: 437554

You will have to save the "current largest number" somewhere when you add a page, otherwise (with any solutions that try to find it out on the spot) the performance is going to be atrocious.

For a slow implementation that's still less slow than others you may come up with, you can use this:

$files = scandir('.'); // assume we are looking in the current directory
natsort($files);
$largest = intval(end($files)); // sample value: "415"

Upvotes: 3

Related Questions