1

I would like some help in converting a string to an array and performing foreach on the array data.

Currently in my view I echo my string <?php echo $p['tags']; ?>

and this gives me the following data news, latest

I would like to do a foreach on this data so that I can wrap the values in <a href=""></a>

How is this done? What is the best method?

2 Answers 2

3

Explode them into an array:

<?php

$all_tags = explode( ',' , $p['tags'] );

foreach ( $all_tags as $one_tag ){
    echo '<a href="#">' . $one_tag . '</a>';
}

The explode() function splits the string using a delimiter (in this case the ',' comma) and each item is passed into the array.

Sign up to request clarification or add additional context in comments.

Comments

0

I'm not sure I understand what you're asking correctly. Is this what you want?

$var = 'news, lastest';
$tmp = explode(', ', $var);

$result = '<a href="#">'.implode('</a>, <a href="#">', $tmp).'</a>';

var_dump($result);
// string(42) "<a href="#">news</a>, <a href="#">lastest</a>"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.