Search code examples
phpimplode

Can you do implode .= in php?


Not sure if I ask this correctly, correct me if I am wrong. I know you need an array to do implode, Instead adding a space after </a>, I want to do an implode in .=

for ($i=1; $i<=$lastPage; $i++) {  
    $pageLink .= "<a href='ajax.php?action=merchantlist&merchant_id=" . $merchant_id . "p=".$i."'>".$i."</a>";  
};  
$pageLinks = implode(' ', $pageLink);

Solution

  • .= Means to append to the previously defined variable (string mostlikely). So in your case you are alrady craeting a string out of your loop to the exception that your variable has not been initialized.

    So you could do something like this and remove the implode:

    $pageLink="";
    for ($i=1; $i<=$lastPage; $i++) {  
        $pageLink .= "<a href='ajax.php?action=merchantlist&merchant_id=" . $merchant_id . "p=".$i."'>".$i."</a>";  
    };  
    echo $pageLink;
    

    or create an array (like your original question is asking for) but i think it is an unessecary step. (initalize an array, to call an function to make the string) as when you could just use 1 varaible and avoid the function threshold by appending to it (like in my 1st snippet).

    for ($i=1; $i<=$lastPage; $i++) {  
        $pageLink[] = "<a href='ajax.php?action=merchantlist&merchant_id=" . $merchant_id . "p=".$i."'>".$i."</a>";  
    };  
    $pageLinks = implode(' ', $pageLink);
    
        echo $pageLinks;
    

    also i think you are missing an & in your string before the "p="

    $pageLink .= "<a href='ajax.php?action=merchantlist&merchant_id=" . $merchant_id . "p=".$i."'>".$i."</a>";  
    

    should be with an & before the p= like so

    $pageLink .= "<a href='ajax.php?action=merchantlist&merchant_id=" . $merchant_id . "&p=".$i."'>".$i."</a>";  
    

    Another thing, i would url_encode anything in your href that could be a string so an appostrophe won'T break your html attribute.