Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

PHP Array - If Key Begins With

10:57 am on Jan 24, 2017 (gmt 0)

Junior Member

10+ Year Member

joined:Sept 11, 2008
posts: 192
votes: 0

I have this array (it has lots more values in reality). Some of the keys may change from time to time for example Std UK Dom could be Std UK Dom_5 or something similar. I am not sure what these could be but they will always start the same.

$new_shipping_methods = array(
'Std UK Dom' => 'Standard Shipping: 3-5 Days',
'Std UK Dom_2' => 'Standard Shipping: 3-5 Days',
'Std UK Europe 1' => 'Standard Shipping: 5-10 Days',
'Std UK Europe 2' => 'Standard Shipping: 5-10 Days',
'Std UK Europe 3' => 'Standard Shipping: 5-10 Days');

Is there a way to change it to something like this so that the value will be set if the key begins in a certain way:

$new_shipping_methods = array(
[if key begins with Std UK Dom_2] => 'Standard Shipping: 3-5 Days',
[if key begins with std UK Europe] => 'Standard Shipping: 5-10 Days',);
12:38 am on Jan 25, 2017 (gmt 0)

Junior Member

10+ Year Member

joined:June 6, 2006
votes: 2

Think of your $new_shipping_methods array as sort or a storage db. So from what I gather, you want to access that information based on a condition. So here is my thought. I'm old school so bare with me. But this is what I came up with, with the quickness. ;)

$new_shipping_methods = array('key' => 'value', 'key2' => 'value2', 'key3' => 'value3') //stored and ready to search

$condition = $_POST['condition']; //store the condition to find a match

if (array_key_exists($condition, $new_shipping_methods)) {
echo $new_shipping_methods[$condition];

Would it not make sense to just match the condition to the key and output the value regardless? Just my $0.02.
12:51 am on Jan 25, 2017 (gmt 0)

Moderator from US 

WebmasterWorld Administrator lifeinasia is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Dec 10, 2005
votes: 146

I don't think the OP's example conveyed what he wants. Think wildcards (% in SQL parlance). Something like:
$new_shipping_methods = array(
[if key like 'Std UK Dom%'] => 'Standard Shipping: 3-5 Days',
[if key like 'Std UK Europe%'] => 'Standard Shipping: 5-10 Days',);

The following function, based on preg_grep, may do what you want:
function preg_grep_keys($pattern,$input,$flags = 0)
$keys = preg_grep($pattern,array_keys($input),$flags);
$vals = array();
foreach ($keys as $key)
$vals[$key] = $input[$key];
return $vals;

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members