Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

PHP If... else/ for

Options
  • 06-12-2013 4:09pm
    #1
    Registered Users Posts: 23,641 ✭✭✭✭


    I have a simple piece of code that runs through an xml film and echos the required content.

    I use an if statement and put a limit to it of 100.

    The statement runs thought the top 100 xml items and based on the conditions returns all of the results in that 100 items.

    However I want to go thought the whole xml file, but only print the first 5 items within the require condition.

    code looks something like this

    [PHP]$limit = 100;

    for($x=0;$x<$limit;$x++) {
    declarations of various items in the xml file e.g.
    $name = str_replace(' & ', ' & ', $feed[$x]);


    if (condition) {
    do something

    }else{
    do something else
    }
    }[/PHP]

    The else statement will go through the statement 100 times. Should I be even using an if statement for this?


Comments

  • Registered Users Posts: 400 ✭✭irishbuzz


    Elmo wrote: »
    I use an if statement and put a limit to it of 100.

    Is this a typo? The for statement is limiting it to 100.

    If you only want to print the first five you just need a single if statement checking the value of x with no else.

    Something like:

    [PHP]<?php
    $limit = 100;

    for ($x = 0; $x < $limit; $x++) {
    $name = str_replace(' & ', ' & ', $feed[$x]);
    if ($x < 5) {
    echo($name);
    }
    }[/PHP]


  • Registered Users Posts: 23,641 ✭✭✭✭Elmo


    irishbuzz wrote: »
    Is this a typo? The for statement is limiting it to 100.

    If you only want to print the first five you just need a single if statement checking the value of x with no else.

    Something like:

    [PHP]<?php
    $limit = 100;

    for ($x = 0; $x < $limit; $x++) {
    $name = str_replace(' & ', ' & ', $feed[$x]);
    if ($x < 5) {
    echo($name);
    }
    }[/PHP]

    thanks but when I do that it just looks like I could have set the limit to 5.

    I want to be able to read the full xml file (can I set limit to EoF?)
    If any name = Elmo then display
    but only print the first 5 items with that condition


  • Registered Users Posts: 26,556 ✭✭✭✭Creamy Goodness


    depending what way you're reading your xml but you should be using a foreach to iterate over each object in the xml, then you can do something like....
    $i = 0;
    foreach($xml['person'] as $person) {
        if ($person->name == 'Elmo' && $i < 5) {
            echo $xmlObject->name;
            $i++;
        }
    }
    

    my php is rusty at best but the theory should help you.


Advertisement