0

In my $_POST array, I have the following values:

[txtPe_20_Table1] => 2.3
[txtPa_12_Table1] => 0.00
[txtPa_25_Table1] => 0.00
[txtPa_35_Table1] => 0.00
[txtPa_50_Table1] => 0.00
[txtPa_100_Table1] => 0.00
[txtPa_200_Table1] => 0.00
[txtPr_12_Table1] => 0.00

Now, what I want to do is extract only the number values from the keys starting with 'txtPa_'.

What would be the best approach to do this? Should I use regex or just loop through the array searching for a substr beginning with 'txtPa_'?

1
  • 2
    i would change the form to group txtPa together in to an array. otherwise a foreach loop and look at the key Commented Jun 7, 2015 at 22:37

1 Answer 1

3

while it would be best to structure the form so you get the keys grouped together. if you can't then you can do this:

foreach($_POST as $key=>$var){
  if(substr($key, 0, 6)=='txtPa_'){
  //so something with $var
  }
}

from @Rizier123

$filtered = array_filter(function($k){ return strpos($k, "txtPa_") === 0; },ARRAY_FILTER_USE_KEY);

form change option

..

<input type="text" name="txtPa[12_Table1]">
<input type="text" name="txtPa[25_Table1]">

etc then you have the array $_POST[txtPa]

Sign up to request clarification or add additional context in comments.

2 Comments

Or simple an array_filter() call with the flag for keys :) (PHP >=5.6)
If you want to add it to your answer: $filtered = array_filter(function($k){ return strpos($k, "txtPa_") === 0; }, ARRAY_FILTER_USE_KEY);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.