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)) {
strpos
if (strpos($key, 'Google.ca') === 0) {
Note: we're checking to see if the beginning of the string matches Google.ca
, using ===
.
Answered By - steadweb
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.