Skip to content
Advertisement

PHP — identifying last key in foreach to eleminate last delimeter

I’ve been trying to get this to work and while I have tried many methods posted on this site on other pages, I can’t get any of them to work.

I need to identify the last key so that my results don’t have a , at the end. This sounds like such and easy task but I just cant seem to get it to work! At this point I’m guessing I’ve just had a typo or something that I overlooked. Any help would be greatly appreciated.

This is what I have:

<?php
    $searchString = $_GET["s"];  
    $prefix = 'http://link_to_my_xml_file.xml?q=';
    $suffix = '&resultsPerPage=100';
    $file = $prefix . $searchString . $suffix;
    if(!$xml = simplexml_load_file($file))
        exit('False'.$file);
    foreach($xml->results->result as $item) {
        echo $item->sku . ",";
    }
?>

Now this works just fine, it just has a , at the end:

12345,23456,34567,45678,

For reference my xml file is laid out like: results->result->sku, but with a lot more mixed in. I’m just singling out the fields.

Advertisement

Answer

Consider identifying the first instead?

$first = true;
foreach($xml->results->result as $item) {
    if ($first) {
        $first = false;
    } else {
        echo ',';
    }
    echo $item->sku;
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement