On my website, we can create a product with an unknown number of custom field. To insert my data inside the database, I want to know the number of inputs starting with "parameter" (in my data below).
How can I count() the POST result starting with "parameter"? Thanks
array(6) {
["quantity"]=> string(8) "200"
["price"]=> string(4) "150"
["product_supplier"]=> string(4) "1"
["parameter1"]=> string(4) "text"
["parameter2"]=> string(7) "Exemple"
["parameter3"]=> string(4) "text"
}
Use array_keys
to get the keys of the array, and then iterate through using a foreach
or array_reduce
eg
$count = 0;
foreach (array_keys($array) as $key) {
if (strpos($key, 'parameter') === 0) $count++;
}
echo "$count parameters\n";
$count = array_reduce(array_keys($array), function ($c, $v) {
if (strpos($v, 'parameter') === 0) $c++;
return $c; },
0);
echo "$count parameters\n";
Output (for your sample data):
3 parameters
You might instead want to consider naming your parameter inputs using PHP's array notation eg
<input type="text" name="parameters[]" />
Then all your parameter inputs will appear as an array in $_POST['parameters']
and you can get the count easily via
echo count($_POST['parameters']);
It will probably make it easier to process the parameters too as you can use a simple foreach
:
foreach ($_POST['parameters'] as $parameter) {
// do stuff
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.