Extract elements from an array which have a common substring in the key names

Hi

My problem is easily stated, but I can’t figure out how to do it.

a $_POST array has the following elements :-

first–>‘Ann Other’, price–>21, chk_21–>21, chk_x–>24, chk_19–>19, converting–>yes, chk_37–>37

I want to pull out all elements with names containing the “chk” substring into another array:-

$index = array(chk_21–>21, chk_x–>24, chk_19–>19, chk_37–>37)

Can you help me?

Use preg_match to find the keys and place them in the new array($index) with the corresponding values.
Here is an example:

<?php
   if(sizeof($_POST))
   {
	   echo "<pre>";
	   print_R($_POST);
	   $index = array();
	   foreach($_POST as $key => $val)
	   {
		   if(preg_match("/^chk/", $key)) $index[$key] = $val;
	   }
	   print_R($index);
	
	   exit;
   }
   echo '
<form method="post" action="extract_keys.php"><br/>
first: <input type="text" name="first" value="Ann Other" /><br/>
price: <input type="text" name="price" value="21" /><br/>
chk_21: <input type="text" name="chk_21" value="21" /><br/>
chk_x: <input type="text" name="chk_x" value="24" /><br/>
chk_19: <input type="text" name="chk_19" value="19" /><br/>
converting: <input type="text" name="converting" value="yes" /><br/>
chk_37: <input type="text" name="chk_37" value="37" /><br/>
<input type="submit" value="Send" /><br/>
</form>
';
?>

If like me you do not like using preg_match() try this:



$index=array();

foreach( $_POST as $key => $value):

  if ('chk' === substr($key, 0 , 3) )
  {
     $new[$key] = $value;
  }	

endforeach;

echo '<pre>';	
  print_r( $index );
echo '</pre>';	


Output:

Array
(
[chk_21] => 21
[chk_x] => 24
[chk_19] => 19
[chk_37] => 37
)

Hi tom8 & John_Betong - pretty neat…

I am most grateful to both of you - where did you ever find these tricks. I had always assumed that a variable’s name couldn’t be changed

@chelse

I found the tricks from various forums.

I am not sure what you mean by a “variable’s name couldn’t be changed”.

I checked my code and noticed that the online editing had an error so here is the correct script:




$index=array();

foreach( $_POST as $key => $value):

  # I want to pull out all elements with names containing the "chk" substring into another array
  if ('chk' === substr($key, 0 , 3) )
  {
     $index[$key] = $value;
  }

endforeach;

echo '<pre>';
  print_r( $index );
echo '</pre>';