• Sign in to Neowin Faster!

    Create an account on Neowin to contribute and support the site.

  • 0
Sign in to follow this  

[PHP] Move certain array keys

Question

KindredHyperion    0

Is there a quick 'n' easy way of moving certain array keys from one array to another, but only those that match a regex pattern?

What I'm trying to do is make a multi-row type thing without a database, where the script asks the user how many rows they'd like and then gives them that many rows to fill in, each field name being row1, row2, row3, etc.

Then I end up with

$_POST = Array( 'somefield' => 'value', 'anotherfield' => 'value', 'row1' => 'rowvalue1', 'row2' => 'row2value', 'row3' => '3rowval' )

I want to get the row keys into a separate array so I can do a foreach() with the array.

Is this possible? Or does anyone have any easier way I could do this?

Share this post


Link to post
Share on other sites

2 answers to this question

Recommended Posts

  • 0
DjmUK    0

Never touched regex before, and the '=>' symbol has always confused me.

However, session arrays can do as you ask - requires a lot of logic, and creating your own unique key index for the session, but it does work. For example, it's how I write shopping carts - storing arrays of data into a session and then extracting the information and organising the data using a foreach loop. If this is the sort of thing you're after, then scan google for 'php session arrays' and have fun - otherwise, sorry - I've lost it again ;)

Share this post


Link to post
Share on other sites
  • 0
GatorV    1

You can play with this function:

function array_search_keys_regex( $input_array, $pattern ) {
	$keys = array_keys( $input_array );
	$matches = array();
	foreach( $keys as $key ) {
		if( preg_match( $pattern, $key ) ) {
			$matches[] = $input_array[$key];
		}
	}

	return $matches;
}

This function doesn't "move" rathern matches a regex pattern and returns those values that match the key :)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.