PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, January 12, 2022

[FIXED] Array_key_exist of matching keyword

 January 12, 2022     php, yii     No comments   

Issue

I have an array as follows stored in variable $keyword_reports_data

[interne] => Array
             (
                [Google.ca - Canada] => Array (...) 
                [Google.com - USA] => Array (...)
             )

i have code like this to search(not exactly for example)

foreach ($keyword_reports_data['interne'] as $key => $value) {
   if (array_key_exists("Google.ca", $value)) {
      echo "hi " ;exit;
   }   
   else {
      echo  "not exist "; exit;
   }
}

But actually it will print

not exist

how to print "hi" if array value exist like keyword "Google.ca" only with "Google.ca" not with "Google.ca - Canada" so i need to put condition for this


Solution

The key differs within the array. Change the key from "Google.ca" to "Google.ca - Canada".

Exact match

If you want to match the key exactly, use array_key_exists.

Change the if statement to:

if (array_key_exists("Google.ca - Canada", $value)) {

Partial match

If you want to check whether the key contains part of a string, either use preg_match or strpos. Regular expressions can be slow, hence the suggestion of using strpos.

Examples below:

preg_match

if (preg_match('/Google.ca/', $key)) {

https://3v4l.org/CcMt7

strpos

if (strpos($key, 'Google.ca') === 0) {

https://3v4l.org/QB1kT

Note: we're checking to see if the beginning of the string matches Google.ca, using ===.



Answered By - steadweb
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing