Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Iterate through $_POST and use values by name

Tags:

arrays

php

I have a form that contains a number of fields with names item1, item2, item13, item43 etc, each time those fields are different because they are populated in the form with AJAX.

When user submits I need to perform the following:

  foreach($_POST['itemX']['tagsX'] as $tag){     inserttag($tag, X);   } 

where X = 1,2,13,43 etc. How can I iterate the $_POST values and perform the above only for the values of those that their name begins with 'item' followed by an the X identifier?

Solution based on Piontek's answer:

The posted data has the following format:

[item38] => Array([tags38] => Array([0] => aaa,[1] => bbb)) [item40] => Array([tags40] => Array([0] => ccc,[1] => ddd)) [item1] =>  Array([tags1] => Array([0] => eee,[1] => zzz)) 

And this is how I parse and use it:

foreach($_POST as $key => $value){     if (strstr($key, 'item')){         $id = str_replace('item','',$key);          foreach($_POST['item'.$id]['tags'.$id] as $tag){             inserttag($tag, $id);         }        } } 
like image 902
bikey77 Avatar asked Jan 09 '13 20:01

bikey77


1 Answers

foreach($_POST as $key => $value) {     if (strstr($key, 'item'))     {         $x = str_replace('item','',$key);         inserttag($value, $x);     } } 
like image 186
Kyle Avatar answered Sep 30 '22 21:09

Kyle