Alex
Alex

Reputation: 1

Want to create a ul li from some comma seperated values

currently i have some comma seperated values like

"oranges, apples, pies"

and i want to turn those into a list like this

hope anyone can help me here

Upvotes: 0

Views: 1359

Answers (3)

binaryLV
binaryLV

Reputation: 9122

$data = "oranges, apples, pies";
$data = explode(',', $data);
echo '<ul>';
foreach ( $data as $item ) {
    echo '<li>', trim($item), '</li>';
}
echo '</ul>';

[sarcasm=on] For those who are looking for unmaintainable, hard-to-read code with no complex stuff like arrays and looping through them (yeah, I know, string technically is a kind of array, though it's different from what usually is meant with arrays):

$input = 'oranges, apples, pies';
$output = '';

$output = '<ul><li>';
$inputLength = strlen($input);
$skipSpaces = true;
for ( $n = 0; $n < $inputLength; ++$n ) {
    if ( $skipSpaces ) {
        if ( $input[$n] === ' ' ) {
            continue;
        }
        $skipSpaces = false;
    }
    if ( $input[$n] === ',' ) {
        $skipSpaces =  true;
        $output .= '</li><li>';
        continue;
    }
    $output .= $input[$n];
}
$output .= '</li></ul>';

var_dump($output);

Upvotes: 8

Wh1T3h4Ck5
Wh1T3h4Ck5

Reputation: 8509

$slist = "oranges, apples, pies";
echo "<ul><li>" . str_replace(", ", "</li><li>", $slist) . "</li></ul>";  

Upvotes: 2

Gordon
Gordon

Reputation: 316969

Will only add none yet mentioned possibilities:

printf(
    '<ul><li>%s</li></ul>',
    implode(
        '</li><li>',
        str_getcsv("oranges, apples, pies")
    )
);

though str_getcsv is somewhat overkill if you dont have multiple rows and enclosing chars and stuff like that. Can just as well just use explode then.

Yet another possibility:

echo '<ul>';
$tok = strtok("oranges, apples, pies", ',');
while ($tok !== false) {
    echo '<li>', trim($tok), '</li>';
    $tok = strtok(',');
}
echo '</ul>';

And another one:

$dom = new DOMDocument;
$dom->appendChild(
    $dom->createElement('ul')
);
foreach(explode(',', 'oranges, apples, pies') as $fruit) {
    $dom->documentElement->appendChild(
        $dom->createElement('li', $fruit)
    );
}
$dom->formatOutput = TRUE;
echo $dom->saveXml($dom->documentElement);

And a final one:

$writer = new XMLWriter();
$writer->openURI('php://output');
$writer->startElement('ul');
foreach(explode(',', 'oranges, apples, pies') as $fruit) {
    $writer->writeElement('li', $fruit);
}
$writer->endElement();

Upvotes: 1

Related Questions