View Full Version : Help needed with foreach/arrays for tagging

01-30-2007, 11:37 AM
I need some help with foreach/arrays - I want to add a small tagging function to a news script, but so far it's not working.

I either get the error "Warning: Invalid argument supplied for foreach() on line 54"
or it enters the data as "charts, tags, testing" into the database in only one row, instead of creating a new row for each of those tags.

I have defined a $tags = array(); at the top if my file, and I have a simple text input field for typing the tags.

This is the part of the script which posts the tags:

$tags = $_POST['tags'];
foreach($tags as $tag) {
$tag = strtolower($tag);
$tag = strip_tags($tag);
$tag = str_replace('ä', "ae", $tag);
$tag = str_replace('ö', "oe", $tag);
$tag = str_replace('ü', "ue", $tag);
$tag = str_replace('ß', "ss", $tag);
$tag = mysql_real_escape_string($tag);
$query_tag = "INSERT INTO news_tags VALUES ('','$newsID','$tag')";
$result_tag = mysql_query($query_tag);
if ($result_tag != false) {
echo "<br />Tag '".$tag."' hinzugefügt.";

Can anyone help out and explain how I get a new entry for each comma seperated tag in my input field?

01-30-2007, 12:47 PM
Hi if you have defined $tags = array(); at the top of the file it will get over re-set at the point where you set it to the posted var (at this point: $tags = $_POST['tags'];).

You are getting "Warning: Invalid argument supplied for foreach() on line 54" because if the post'ed tags value is empty it will not be an array.

You can stop this one of 2 ways:

first is the quickest to code but can be confusing for some is using the Ternary Operator (http://php.net/operators.comparison)

replace the line

$tags = $_POST['tags'];


$tags = (is_array($_POST['tags']) ? $_POST['tags'] : array());

second slightly longer but more readable:

$tags = $_POST['tags'];
$tags = array();
// your code

Hope this helps.