Search code examples
phparraysxmlmatchsentence

PHP check value in array match conditions then echo out that specific values


I'm trying to display movie information from the XML list that matches post title.

$movie_title is the variable of the movie name.

Now I have 2 problems:

  • If title doesn't match then else statement will echo out "No match!" for each move that doesn't match condition of the if statement.

  • How to limit result only on the first movie that match the title.

I'm also wondering if there is some better way to do this.

$movie_title = get_the_title();
$movies = simplexml_load_file('http://www.kolosej.si/spored/xml/2.0/');

foreach($movies as $movie) {

    $movie_list = $title=$movie->title;

    if((strpos($movie_list, $movie_title)) !== false) {

        echo $original_title=$movie->original_title . '<br>';
        echo $description=$movie->plot_outline;

    } else {
        echo 'No match!';
    }
}

Solution

  • This would work, by setting a $found when you actually find a matching movie title and only outputting a No Match if the $found is not set

    <?php
    $movie_title = get_the_title();
    $movies = simplexml_load_file('http://www.kolosej.si/spored/xml/2.0/');
    $found = false;
    
    foreach($movies as $movie) {
    
        $movie_list = $title=$movie->title;
    
        if((strpos($movie_list, $movie_title)) !== false) {
    
            echo $original_title=$movie->original_title . '<br>';
            echo $description=$movie->plot_outline;
            $found = true;
            break;  // assuming there will only be one, else leave this out
        }
    
    }
    if ( ! $found ) {
        echo 'No match!';
    }