How to do a tag system?

Ok, this is a part of PHP that i’ve nevr done before so can someone explain to me how to do a tag system because im building a simple blog script and right now my code is

<div class="form-group"> <label>Tags (max 15, separate with comma):</label> <input class="form-control" name="tags[features]" value="<?php echo $productDetails['tags'];?>" id="coupon-code" type="text"></div>

The php code is

$tags = $_POST['tags'];

but basically i dont know how to do an array as such and then at the end the final result is something like but right now i don’t know how to do it so pleae can someone point me in the right direction / help me achieve a tags system!


or something like sitepoint tags system


If you are wanting an array from the form result you can do this with explode()
Because the user is not inputting an array, but a CSL which comes as a single value, I’m not sure you need the [] in the input name.

$limit = 8;
$raw = explode(',', $_POST['tags'], $limit) ;
$tags = array();
foreach($raw as $tag){ $tags[] = trim($tag) ;}

I used just a comma for the delimiter, then run trim() on each entry, just because you can’t trust users to always use a space or not with the comma.

Though you may want to create a custom function to sanitise the inputs more (Eg, with a preg_replace() to limit allowed characters). In which case you could use array_walk() instead of the slightly cumbersome foreach and do it all in one hit.

Set and use $limit only if you want to limit the number of tags, it is optional.

1 Like

I think you are confusing the HTML form’s post and get methods.

Submitting a post method passes a hidden $_POST array to the HTML form’s action page. Setting the form’s method to get passes the input named settings to the command line which is useful for web page tags.

A useful function for displaying variable, arrays, booleans’ strings, etc I frequently use :slight_smile:

function fred( $val ) // easy to type
echo '<pre style="width:88%; margin: 2em auto;">';
print_r( $val );
echo '</pre>';

// Usage
fred ( $_POST );
fred ( $_GET );

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.