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:

    $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))
    foreach($xml->results->result as $item) {
        echo $item->sku . ",";

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


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.


Consider identifying the first instead?

$first = true;
foreach($xml->results->result as $item) {
    if ($first) {
        $first = false;
    } else {
        echo ',';
    echo $item->sku;

Answered By – Rowenia

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published