fefe
fefe

Reputation: 9055

php loops on compare

I have problems with my abc loop. I compare 2 loops, if strings are matching I embed between hyperlink but how would I would avoid to do not show the looped items twice.

<?php
    foreach($this->data->lexikon_index() as $index){
        foreach ($abc as $letter){      
            echo '<li>';
            if ( $index->alpha == $letter ){
                echo "<a href=\"#{$index->alpha}\">{$index->alpha}</a>";
            } else {
                echo $letter;
            }

            echo '</li>';
        }

        $lexikon_content[] = $this->data->lexikon_content($index->alpha);
    }
    echo '</ul>';
?>

Upvotes: 0

Views: 80

Answers (2)

Jack M.
Jack M.

Reputation: 1170

With your code you are doing a lot of looping. Personally I would try this (if I read your code right):

<?php
    $lexikon_content = array();
    foreach ($this->data->lexikon_index() as $index) {        
        $lexikon_content[count($lexikon_content)] = $this -> data -> lexikon_content($index -> alpha);
    }
    foreach ($abc as $letter) {
        echo '<li>';
        if (in_array($letter, $lexikon_content)) {
            echo "<a href=\"#".$letter."\">".$letter."</a>";
        } else {
            echo $letter;
        }
        echo '</li>';
    }

    echo '</ul>';
?>

Upvotes: 0

SeanWM
SeanWM

Reputation: 16989

Use an array to store variables that you have already used. Then use !in_array():

<?php
    unset($used);
    foreach ($this->data->lexikon_index() as $index) {
        foreach ($abc as $letter) {
            echo '<li>';
            if ($index -> alpha == $letter && !in_array($letter, $used)) {
                $used[] = $letter;
                echo "<a href=\"#{$index->alpha}\">{$index->alpha}</a>";
            } else {
                echo $letter;
            }
            echo '</li>';
        }
        $lexikon_content[] = $this -> data -> lexikon_content($index -> alpha);
    }
    echo '</ul>';
?>

Upvotes: 2

Related Questions