How to check the array key matches specific string in php - php

$array = array(
"[ci_id]" => '144309',
"[NEW flag]" => 'No',
"[[*PRODUCT_IMAGE_ANCHOR1*]]" => ,
"[[*PRODUCT_IMAGE2*]]" => '154154154'
);
I need to get the elements which have pattern like '[['.
I have tried by using array_key_exists():-
if (array_key_exists('[*PRODUCT_IMAGE2*]', $array))
But i want to match only with '['
Can any one help me on this

Use preg_grep() with array_keys() like below:-
$matches = preg_grep ('/[.*?]/i', array_keys($array));
print_r($matches);
Output:- https://eval.in/817299
Or can do it using strpos() also:-
foreach($array as $key=>$val){
if(strpos($key,'[')!== false){
echo $key ."is matched with [*] pattern";
echo PHP_EOL;
}
}
Output:- https://eval.in/817297

The following code will give the true for the key with double [[ in if you know the element index value
$test = array("a"=>'a',"[a]"=>'a',"[[a]]"=>'a',"b"=>'b',"c"=>'c');
var_dump(array_key_exists("[[a]]", $test));
If you can checking the keys to determine if [[ even exist then the following code should work
$test = array("a"=>'a',"[a]"=>'a','[[a]]'=>'a',"b"=>'b',"c"=>'c');
$values = array();
foreach ($test as $key=>$value) {
if (stripos('[[', substr($key, 0, 2)) !== false) {
array_push($values, $value);
}
}

Related

replace all keys in php array

This is my array:
['apple']['some code']
['beta']['other code']
['cat']['other code 2 ']
how can I replace all the "e" letters with "!" in the key name and keep the values
so that I will get something like that
['appl!']['some code']
['b!ta']['other code']
['cat']['other code 2 ']
I found this but because I don't have the same name for all keys I can't use It
$tags = array_map(function($tag) {
return array(
'name' => $tag['name'],
'value' => $tag['url']
);
}, $tags);
I hope your array looks like this:-
Array
(
[apple] => some code
[beta] => other code
[cat] => other code 2
)
If yes then you can do it like below:-
$next_array = array();
foreach ($array as $key=>$val){
$next_array[str_replace('e','!',$key)] = $val;
}
echo "<pre/>";print_r($next_array);
output:- https://eval.in/780144
You can stick with array_map actually. It is not really practical, but as a prove of concept, this can be done like this:
$array = array_combine(
array_map(function ($key) {
return str_replace('e', '!', $key);
}, array_keys($array)),
$array
);
We use array_keys function to extract keys and feed them to array_map. Then we use array_combine to put keys back to place.
Here is working demo.
Here we are using array_walk and through out the iteration we are replacing e to ! in key and putting the key and value in a new array.
Try this code snippet here
<?php
$firstArray = array('apple'=>'some code','beta'=>'other code','cat'=>'other code 2 ');
$result=array();
array_walk($firstArray, function($value,$key) use (&$result) {
$result[str_replace("e", "!", $key)]=$value;
});
print_r($result);
If you got this :
$firstArray = array('apple'=>'some code','beta'=>'other code','cat'=>'other code 2 ');
You can try this :
$keys = array_keys($firstArray);
$outputArray = array();
$length = count($firstArray);
for($i = 0; $i < $length; $i++)
{
$key = str_replace("e", "!", $keys[ $i ]);
$outputArray[ $key ] = $firstArray[$keys[$i]];
}
We can iterate the array and mark all problematic keys to be changed. Check for the value whether it is string and if so, make sure the replacement is done if needed. If it is an array instead of a string, then call the function recursively for the inner array. When the values are resolved, do the key replacements and remove the bad keys. In your case pass "e" for $old and "!" for $new. (untested)
function replaceKeyValue(&$arr, $old, $new) {
$itemsToRemove = array();
$itemsToAdd = array();
foreach($arr as $key => $value) {
if (strpos($key, $old) !== false) {
$itemsToRemove[]=$key;
$itemsToAdd[]=str_replace($old,$new,$key);
}
if (is_string($value)) {
if (strpos($value, $old) !== false) {
$arr[$key] = str_replace($old, $new, $value);
}
} else if (is_array($value)) {
$arr[$key] = replaceKeyValue($arr[$key], $old, $new);
}
}
for ($index = 0; $index < count($itemsToRemove); $index++) {
$arr[$itemsToAdd[$index]] = $itemsToRemove[$index];
unset($arr[$itemsToRemove[$index]]);
}
return $arr;
}
Another option using just 2 lines of code:
Given:
$array
(
[apple] => some code
[beta] => other code
[cat] => other code 2
)
Do:
$replacedKeys = str_replace('e', '!', array_keys($array));
return array_combine($replacedKeys, $array);
Explanation:
str_replace can take an array and perform the replace on each entry. So..
array_keys will pull out the keys (https://www.php.net/manual/en/function.array-keys.php)
str_replace will perform the replacements (https://www.php.net/manual/en/function.str-replace.php)
array_combine will rebuild the array using the keys from the newly updated keys with the values from the original array (https://www.php.net/manual/en/function.array-combine.php)

PHP array_key_exists key LIKE string, is it possible?

I've done a bunch of searching but can't figure this one out.
I have an array like this:
$array = array(cat => 0, dog => 1);
I have a string like this:
I like cats.
I want to see if the string matches any keys in the array. I try the following but obviously it doesn't work.
array_key_exists("I like cats", $array)
Assuming that I can get any random string at a given time, how can I do something like this?
Pseudo code:
array_key_exists("I like cats", *.$array.*)
//The value for cat is "0"
Note that I want to check if "cat" in any form exists. It can be cats, cathy, even random letter like vbncatnm. I am getting the array from a mysql database and I need to know which ID cat or dog is.
You can use a regex on keys. So, if any words of your string equal to the key, $found is true. You can save the $key in the variable if you want. preg_match function allows to test a regular expression.
$keys = array_keys($array);
$found = false;
foreach ($keys as $key) {
//If the key is found in your string, set $found to true
if (preg_match("/".$key."/", "I like cats")) {
$found = true;
}
}
EDIT :
As said in comment, strpos could be better! So using the same code, you can just replace preg_match:
$keys = array_keys($array);
$found = false;
foreach ($keys as $key) {
//If the key is found in your string, set $found to true
if (false !== strpos("I like cats", $key)) {
$found = true;
}
}
This should help you achieve what you're trying to do:
$array = array('cat' => 10, 'dog' => 1);
$findThis = 'I like cats';
$filteredArray = array_filter($array, function($key) use($string){
return strpos($string, $key) !== false;
}, ARRAY_FILTER_USE_KEY);
I find that using the array_filter function with a closure/anonymous function to be a much more elegant way than a foreach loop because it maintains one level of indentation.
You could do using a preg_match with the value not in array but in search criteria
if(preg_match('~(cat|dog)~', "I like cats")) {
echo 'ok';
}
or
$criteria = '~(cat|dog)~';
if (preg_match($criteria, "I like cats")) {
echo 'ok';
}
Otherwise you could use a foreach on your array
foreach($array as $key => $value ) {
$pos = strpos("I like cats", $key);
if ($pos > 0) {
echo $key . ' '. $value;
}
}

Selecting an element in an Associative Array in a different way in PHP

Ok I have this kind of associative array in PHP
$arr = array(
"fruit_aac" => "apple",
"fruit_2de" => "banana",
"fruit_ade" => "grapes",
"other_add" => "sugar",
"other_nut" => "coconut",
);
now what I want is to select only the elements that starts with key fruit_. How can be this possible? can I use a regex? or any PHP array functions available? Is there any workaround? Please give some examples for your solutions
$fruits = array();
foreach ($arr as $key => $value) {
if (strpos($key, 'fruit_') === 0) {
$fruits[$key] = $value;
}
}
One solution is as follows:
foreach($arr as $key => $value){
if(strpos($key, "fruit_") === 0) {
...
...
}
}
The === ensures that the string was found at position 0, since strpos can also return FALSE if string was not found.
You try it:
function filter($var) {
return strpos($var, 'fruit_') !== false;
}
$arr = array(
"fruit_aac"=>"apple",
"fruit_2de"=>"banana",
"fruit_ade"=>"grapes",
"other_add"=>"sugar",
"other_nut"=>"coconut",
);
print_r(array_flip(array_filter(array_flip($arr), 'filter')));
If you want to try regular expression then you can try code given below...
$arr = array("fruit_aac"=>"apple",
"fruit_2de"=>"banana",
"fruit_ade"=>"grapes",
"other_add"=>"sugar",
"other_nut"=>"coconut",
);
$arr2 = array();
foreach($arr AS $index=>$array){
if(preg_match("/^fruit_.*/", $index)){
$arr2[$index] = $array;
}
}
print_r($arr2);
I hope it will be helpful for you.
thanks

Search for a part of an array and get the rest of it in PHP

I've got an array called $myarray with values like these:
myarray = array (
[0] => eat-breakfast
[1] => have-a-break
[2] => dance-tonight
[3] => sing-a-song
)
My goal is to search for a part of this array and get the rest of it. Here is an example:
If i submit eat, I would like to get breakfast.
If i submit have, I would like to get a-break.
I just try but I'm not sure at all how to do it...
$word = 'eat';
$pattern = '/'.$word.'/i';
foreach ($myarray as $key => $value) {
if(preg_match($pattern, $value, $matches)){
echo $value;
}
}
print_r($matches);
It displays:
eat-breakfastArray ( )
But I want something like that:
breakfast
I think I'm totally wrong, but I don't have any idea how to proceed.
Thanks.
use
stripos($word, $myarray)
<?php
$myarray = array (
'eat-breakfast',
'have-a-break',
'dance-tonight',
'sing-a-song'
) ;
function search($myarray, $word){
foreach($myarray as $index => $value){
if (stripos($value, $word) !== false){
echo str_replace(array($word,'-'), "", $value);
}
}
}
search($myarray, 'dance');
echo "<br />";
search($myarray, 'have-a');
echo "<br />";
search($myarray, 'sing-a');
demo
I think the word you seek is at the beginning. Try this
function f($myarray, $word)
{
$len = strlen($word);
foreach($myarray as $item)
{
if(substr($item, 0, $len) == $word)
return substr($item, $len+1);
}
return false;
}
You're feeding the wrong information into preg_match, although I'd recommend using array_search().. Check out my updated snippet:
$word = 'eat';
$pattern = '/'.$word.'/i';
foreach ($myarray as $key => $value) {
if(preg_match($pattern, $value, $matches)){
echo $value;
}
}
print_r($matches);
To get rid of that last bit, just perform a str_replace operation to replace the word with ""
This will both search the array (with a native function) and return the remainder of the string.
function returnOther($search, $array) {
$found_key = array_search($search, $array);
$new_string = str_replace($search . "-", "", $array[$found_key]);
return $new_string;
}

PHP Array values in string?

I have been looking around for a while in the PHP manual and can't find any command that does what I want.
I have an array with Keys and Values, example:
$Fields = array("Color"=>"Bl","Taste"=>"Good","Height"=>"Tall");
Then I have a string, for example:
$Headline = "My black coffee is cold";
Now I want to find out if any of the array ($Fields) values match somewhere in the string ($Headline).
Example:
Array_function_xxx($Headline,$Fields);
Would give the result true because "bl" is in the string $Headline (as a part of "Black").
I'm asking because I need performance... If this isn't possible, I will just make my own function instead...
EDIT - I'm looking for something like stristr(string $haystack , array $needle);
Thanks
SOLUTION - I came up with his function.
function array_in_str($fString, $fArray) {
$rMatch = array();
foreach($fArray as $Value) {
$Pos = stripos($fString,$Value);
if($Pos !== false)
// Add whatever information you need
$rMatch[] = array( "Start"=>$Pos,
"End"=>$Pos+strlen($Value)-1,
"Value"=>$Value
);
}
return $rMatch;
}
The returning array now have information on where each matched word begins and ends.
This should help:
function Array_function_xxx($headline, $fields) {
$field_values = array_values($fields);
foreach ($field_values as $field_value) {
if (strpos($headline, $field_value) !== false) {
return true; // field value found in a string
}
}
return false; // nothing found during the loop
}
Replace name of the function with what you need.
EDIT:
Ok, alternative solution (probably giving better performance, allowing for case-insensitive search, but requiring proper values within $fields parameter) is:
function Array_function_xxx($headline, $fields) {
$regexp = '/(' . implode('|',array_values($fields)) . ')/i';
return (bool) preg_match($regexp, $headline);
}
http://www.php.net/manual/en/function.array-search.php
that's what you looking for
example from php.net
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>

Categories