dimanche 11 juin 2017

Is there a more efficient way to make sure a randomized list doesn't contain a portion of the URL?

I'm looking for a more efficient way to make sure a randomized list of four items (from an array) doesn't contain the filename from the current url.

The solution does not use a database. $relatedArray[$rand_keys[0]] is a standard array created in this .php file. It contains about 100 code snippets and each snippet (item in the array) contains a unique url.

I've come up with the solution below. It works, but I'm guessing there is a more efficient solution. Any suggestions are greatly appreciated.

// How to isolate a filename in a URL - http://ift.tt/2rkBFGH
$fileName =  pathinfo($_SERVER['REQUEST_URI']);

$rand_keys = array_rand($relatedArray, 4);

//Ignore if array value contains variable value. http://ift.tt/2rPINyu
if (strpos($relatedArray[$rand_keys[0]], $fileName['filename']) !== false) {
    echo $relatedArray[$rand_keys[1]] . "\n<br>";
    echo $relatedArray[$rand_keys[2]] . "\n<br>";
    echo $relatedArray[$rand_keys[3]] . "\n<br>";
    } elseif (strpos($relatedArray[$rand_keys[1]], $fileName['filename']) !== false) {
    echo $relatedArray[$rand_keys[0]] . "\n<br>";
    echo $relatedArray[$rand_keys[2]] . "\n<br>";
    echo $relatedArray[$rand_keys[3]] . "\n<br>";
    } elseif (strpos($relatedArray[$rand_keys[2]], $fileName['filename']) !== false) {
    echo $relatedArray[$rand_keys[0]] . "\n<br>";
    echo $relatedArray[$rand_keys[1]] . "\n<br>";
    echo $relatedArray[$rand_keys[3]] . "\n<br>";
    } elseif (strpos($relatedArray[$rand_keys[3]], $fileName['filename']) !== false) {
    echo $relatedArray[$rand_keys[0]] . "\n<br>";
    echo $relatedArray[$rand_keys[1]] . "\n<br>";
    echo $relatedArray[$rand_keys[2]] . "\n<br>";
    } else {
    echo $relatedArray[$rand_keys[0]] . "\n<br>";
    echo $relatedArray[$rand_keys[1]] . "\n<br>";
    echo $relatedArray[$rand_keys[2]] . "\n<br>";
    echo $relatedArray[$rand_keys[3]] . "\n<br>";
}

Aucun commentaire:

Enregistrer un commentaire