Jump to content

[SOLVED] Set new value of array after loop


kaplak

Recommended Posts

I'm sure this must have been covered a thousand times, but can't find anything anywhere about this.

 

I want to get $tags, which is an array with a set of existing values to get the new values from this loop :

 

$search = ";";
$replace = "";
if (count($tags) > 0) {
        foreach ($tags as $tag) {
		echo "LOOP 1:"; echo $tag;
		$cleantag = str_replace($search, $replace, $tag);
		$tag = $cleantag;
		echo "LOOP 2:"; echo $tag;
		$tags[$tag->name] = $cleantag;
		echo "LOOP 3:"; echo $tags[$tag->name];
	}
}

echo "<p>TAGS :</p>"; print_r($tags);

 

The loop works great in that it successfully removes the semicolons, which is verified by echo'ing the values of the individual variables in the loop. Everything seems to go right.

 

But when printing the value of the $tags array after this loop all semicolons are still there.

 

How can I get $tags to contain the new values from the loop?

 

I can't get it into my head, how it would not work. I'm a PHP newbie, but I'm a quick learner.

 

This is used in a WordPress plugin btw, but strikes me as more of a PHP issue, why I post it here, where there's a bigger chance to get help :-)

 

Thanks for your help in advance!

It looks like you were almost there - just going about accessing the array's value in the wrong way. The -> operator is used in object oriented programming to access properties or methods. You need to use the => operator, though in a slightly different way:

 

$search = ";";
   $replace = "";
   if (count($tags) > 0) {
        foreach ($tags as $key => $tag) {
         echo "LOOP 1:"; echo $tag;
         $cleantag = str_replace($search, $replace, $tag);
         $tag = $cleantag;
         echo "LOOP 2:"; echo $tag;
         $tags[$key] = $cleantag;
         echo "LOOP 3:"; echo $tags[$key];
      }
   }
   
   echo "<p>TAGS :</p>"; print_r($tags);

 

Basically, the line foreach ($tags as $key => $tag) says that we're going to loop through each element of the $tags array and, for each element, we'll call the key of the array $key and the value of the array $tag.

 

This thread may help.

Thanks a lot for clearing that up! Thanks for the link!

It works perfectly - $tags is really changed by the loop now!

 

This got me a long way - been struggling to get this working all day. This forum seems like a very good place with lots of very useful advice.

 

Now I face how to get the value of that array into the WordPress database. But that's a different problem :-)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.