1

I am using array_key_exists on an associative array to detect if a key exists like this...

if (array_key_exists('Packaged price (£3.00)', $item))
{
echo 'The Key Exists';
}

This works fine, but I want to modify it so that it checks if the key has packaged in the name. So instead of checking just for 'Packaged price (£3.00)' it would also work for the following...

Packaged cost (£3.00)
Packaged price (£17.00)
Packaged Item

Is this possible?

3 Answers 3

1

Simply loop through all the keys and check if any key contains the term Packaged

foreach($items as $key=>$value)
{
      if(stristr($key,'Packaged')!==FALSE)
         echo "Matching key is: $key";
}

Fiddle

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

Comments

1

array_key_exists will not work in that case it will perform exact match, for your requirement following may be used:

foreach($array as $key=>$val){
   $keyArray = explode(' ',$key);
   if(in_array('Packaged',$keyArray))
      echo "Key exists" ;
}

2 Comments

for ($array as......?
Don't need to explode and create another array. Just use any string function on that key to find out if the key contains the term Packaged
0
$test = "Package sdsd";

echo preg_match("/(Package)+/",$test);

you can use simple regex , as an example above if the Package word occurs the string the result will be true

Comments

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.