Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.
Hi all, please see this major site announcement: https://www.boards.ie/discussion/2058427594/boards-ie-2026

PHP If... else/ for

  • 06-12-2013 03:09PM
    #1
    Registered Users, Registered Users 2 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, Registered Users 2 Posts: 401 ✭✭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, Registered Users 2 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, Registered Users 2 Posts: 26,449 ✭✭✭✭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