Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count Similar Array Keys

Tags:

arrays

post

php

I have a POST request coming to one of my pages, here is a small segment:

[shipCountry] => United States
[status] => Accepted
[sku1] => test
[product1] => Test Product
[quantity1] => 1
[price1] => 0.00

This request can be any size, and each products name and quantity's key would come across as "productN" and "quantityN", where N is an integer, starting from 1.

I would like to be able to count how many unique keys match the format above, which would give me a count of how many products were ordered (a number which is not explicitly given in the request).

What's the best way to do this in PHP?

like image 694
Andrew E. Avatar asked Jan 24 '23 06:01

Andrew E.


2 Answers

Well, if you know that every product will have a corresponding array key matching "productN", you could do this:

$productKeyCount = count(preg_grep("/^product(\d)+$/",array_keys($_POST)));

preg_grep() works well on arrays for that kind of thing.

like image 100
zombat Avatar answered Jan 25 '23 20:01

zombat


What Gumbo meant with his "use array instead" comment is the following:

In your HTML-form use this:

<input type="text" name="quantity[]" />

and $_POST['quantity'] will then be an array of all containing all of your quantities.

If you need to supply an id you can also do this:

<input type="text" name="quantity[0]" />

$_POST['quantity][0] will then hold the corresponding quantity.

like image 27
André Hoffmann Avatar answered Jan 25 '23 21:01

André Hoffmann