1

I have an include on my site that provides a link to narrow a database request for each starting letter, when it is run once on the site it runs fine. However, I would like to include it both at the top and bottom of the page and this seems to cause a problem as it shows each link twice.

Below is the code in the include

<?php
$alphas = range('A', 'Z');
$url =  'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);

foreach ($alphas as $letter) {
    $elements[] = "<a href=$url?firstletter=$letter>$letter</a>";
}
echo implode(', ', $elements);

I have tried checking whether $alphas exists and only running $alphas = range('A', 'Z') if it doesn't but that didn't help.

Any ideas appreciated.

4
  • Initialise $elements before the foreach i.e. $elements = array(); or $elements = []; Commented Feb 2, 2017 at 20:19
  • @RiggsFolly still runs unnecessary loop twice Commented Feb 2, 2017 at 20:21
  • You did init before the loop like this right? $elements = array(); foreach ($alphas as $letter) { ... Commented Feb 2, 2017 at 20:22
  • @nogad Why did you delete your answer Commented Feb 2, 2017 at 20:32

2 Answers 2

2

Just test in the first line of the code if the $elements arrays already exist. Then the second time the code runs, it just explodes the $elements array that was created at the top of the script. No extra variables required!

<?php
if ( ! isset($elements) ) {
    $alphas = range('A', 'Z');
    $url =  'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
    $elements = array();
    foreach ($alphas as $letter) {
        $elements[] = "<a href=$url?firstletter=$letter>$letter</a>";
    }
}
echo implode(', ', $elements);
Sign up to request clarification or add additional context in comments.

Comments

1

This is the code I used to solve the issue, not saying it's the best, just what I used.

<?php
if (!isset($elements)) {
$alphas = range('A', 'Z');
$url =  'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);

foreach ($alphas as $letter) {
    $elements[] = "<a href=$url?firstletter=$letter>$letter</a>";
}
echo implode(', ', $elements);}
else {
    echo implode(', ', $elements);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.