BENN1TH
BENN1TH

Reputation: 2023

String to an array and then foreach

I have a variable string which is passed to an and array then foreach that just does not want to work. Below is the code im using.

$explode = $_obj->getModDependencies();
//this variable will returns/echos the string as @ModA,@Mod_b,@Mod3 etc (yes @ is in each value) 

and the foreach and array php code im using

$arr = array($explode);
foreach ($arr as $value) {
echo '<a href="'.$this->getUrl().'mod?mod_id='.$value.'">'.$value.'</a>';
}

if i use the above code it echos one hyperlink with each value at the end of it (http://myurl/mod?mod_id=@ModA,@Mod_b,@Mod3) but i want to echo each hyperlink for each value.

Which would be

http://myurl/mod?mod_id=@ModA

http://myurl/mod?mod_id=@Mod_b

and so forth.

But if i place the actual variable output string directly into the array it echos out how i want it (see below code that works)

$arr = array(@ModA,@Mod_b,@Mod3);
foreach ($arr as $value) {
echo '<a href="'.$this->getUrl().'mod?mod_id='.$value.'">'.$value.'</a>';
}

Any help wold be awesome!!

Upvotes: 0

Views: 74

Answers (2)

Hanky Panky
Hanky Panky

Reputation: 46910

$arr = array($explode);

Thats the issue, just by saying something is within array() doesnt really make it an array as you expect it to be. You only gave it 1 argument.

You also mentioned the value of $explode is like this @ModA,@Mod_b,@Mod3. Just by naming something $explode doesn't explode it. You have to explode it yourself

$arr=explode(",","@ModA,@Mod_b,@Mod3"); 
//$arr=explode(",",$explode) in your case

Once that is done, your loop is already fine

foreach ($arr as $value) {
echo '<a href="'.$this->getUrl().'mod?mod_id='.$value.'">'.$value.'</a>';
}

Fiddle

Upvotes: 2

empiric
empiric

Reputation: 7878

When your variable $explode will be a string as '@ModA,@Mod_b,@Mod3' then you have to explode it.

$arr = explode(',', $explode);
foreach ($arr as $value) {
    echo '<a href="'.$this->getUrl().'mod?mod_id='.$value.'">'.$value.'</a>';
}

Upvotes: 1

Related Questions