0

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 - https://stackoverflow.com/questions/2183486/php-get-file-name-without-file-extension
$fileName =  pathinfo($_SERVER['REQUEST_URI']);

$rand_keys = array_rand($relatedArray, 4);

//Ignore if array value contains variable value. https://stackoverflow.com/questions/4366730/how-do-i-check-if-a-string-contains-a-specific-word-in-php
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>";
}
Mr. B
  • 2,677
  • 6
  • 32
  • 42

1 Answers1

1

Filter your $rand_keys array with array_filter:

$name = $fileName['filename'];
$rand_keys = array_rand($relatedArray, 4);
$filtered = array_filter(
    $rand_keys,
    function ($v) use ($name) { return strpos($v, $name) === false; }
);
print_r($filtered);
u_mulder
  • 54,101
  • 5
  • 48
  • 64