check if one of multiple values exists in array - php

For array with single values like
array(2) {
["blue"]=>
int(0)
["red"]=>
int(1)
}
I use this code
<?php
if (array_key_exists('blue',$array))
{
echo "jo";
}
?>
But what code do I need to use for arrays like this
array(2) {
["yellow blue"]=>
int(0)
["red white"]=>
int(1)
}
to check if blue exists?

My take:
if(preg_grep('/blue/', array_keys($array))) { echo 'found'; }
Or if you want to get them:
$matches = preg_grep('/blue/', array_keys($array));
print_r($matches);

$partialKey = 'blue';
$byPartialKey = function ($key) use ($partialKey) {
$parts = explode(' ', $key);
return in_array($partialKey, $parts);
};
$result = array_filter (array_keys($input), $byPartialKey);
$result now contains all keys, that somehow contains $partialKey.

you can do using regular expression
search='blue';
foreach ($array as $key => $value) {
if (preg_match('~'.$search.'~i',$key)) {
echo "jo";
}
}
The \b in the pattern indicates a word boundary, so only the distinct
word "blue" is matched, and not a word partial like "bluegreen"
search='blue';
foreach ($array as $key => $value) {
if (preg_match('/\b'.$search.'\b/i',$key)) {
echo "jo";
}
}
Reference

I would do it like this:
function subkey_exists($string, $array) {
foreach($array as $key => $value) {
$sub_keys = explode(" ", $key);
if(in_array($string,$sub_keys)) {
return true;
}
}
return false;
}
[edit]
updated to your requirements

Yet another array_filter solution :
<?php
function find_keys_like($key, $array) {
return array_filter(array_keys($array), function($k) use (&$key) {
return strpos($k, $key) > -1;
});
}
function array_has_key_like($key, $array) {
return count(find_keys_like($key, $array)) > 0;
}
//test
$a = array('blue' => 1, 'yellow blue' => 2, 'green' => 3);
print_r(find_keys_like('blue', $a));
echo 'blue exists ? ' . (array_has_key_like('blue', $a) ? 'yes' : 'no') . PHP_EOL;
/** result :
Array
(
[0] => blue
[1] => yellow blue
)
blue exists ? yes
*/

Related

how can I get my php array data to persist?

When I query the data within the foreach loop it works, but makes a duplicate for each pass in the loop. I try to var_dump it anywhere else outside the loop and the data isn't there. Why won't my data persist outside the forEach loop?
<?php
$old_array = [10-2, 13=>"3452", 4=>"Green",
5=>"Green", 6=>"Blue", "green"=>"green",
"two"=>"green" ,"2"=>"green" , "rulebreak" =>"GrEeN",
"ninja"=>" Green ", ["blue" => "green", "green"=>"green", 2 => "itsGreen"] ];
$newArray = array();
function filter_Green($array) {
$find = "green";
$replace = "not green";
/* Same result as using str_replace on an array, but does so recursively for multi-dimensional arrays */
/* found here:
if (!is_array($array)) {
/* Used ireplace so that searches can be case insensitive */
return str_ireplace($find, $replace, $array);
}
foreach ($array as $key => $value) {
$newArray[$key] = $value;
if ($key == "green") {
$newArray[$key] = "not green";
}
if ($value == "green") {
$newArray[$value] = "not green";
}
}
return $newArray;
}
filter_Green($old_array);
var_dump($newArray);
?>
Expectation: When I run the function it should replace all instances of "green" with "not green" and save those into a $newArray. I have it returning $newArray but even then it doesn't seem to match up that the values are being saved into the newArray, hence why I'm doing var_dump to check if it's even working (it appears to not be)
Results: as it is setup, I get an empty array returned to me...It seems to work somewhat if I move var_dump($newArray) to within the foreach loop but that then duplicates the data for each pass.
if you want var_dump $newArray out side the function then you should declare $newArray as global in your function
<?php
$old_array = [10-2, 13=>"3452", 4=>"Green", 5=>"Green", 6=>"Blue", "green"=>"green", "two"=>"green" ,"2"=>"green" , "rulebreak" =>"GrEeN", "ninja"=>" Green ", ["blue" => "green", "green"=>"green", 2 => "itsGreen"] ];
$newArray = array();
function filter_Green($array) {
global $newArray;
$find = "green";
$replace = "not green";
/* Same result as using str_replace on an array, but does so recursively for multi-dimensional arrays */
if (!is_array($array)) {
/* Used ireplace so that searches can be case insensitive */
return str_ireplace($find, $replace, $array);
}
foreach ($array as $key => $value) {
$newArray[$key] = $value;
if ($key == "green") {
$newArray[$key] = "not green";
}
if ($value == "green") {
$newArray[$value] = "not green";
}
}
return $newArray;
}
filter_Green($old_array);
var_dump($newArray);
?>
But instead of declaring global in function, use returned value by filter_Green($old_array); as below
$result = filter_Green($old_array);
var_dump($result);

isolate string from variable that contains numbers php

I'm trying to isolate text that I've appended to variables that only contain numbers. I've looked it up and I can't find anything that works or is even close to what I'm trying to do. Here's what I'm looking for:
$winning = max(array($var1."Var_One", $var2."Var_Two", $var3."Var_Tree", $var4."Var_Four"));
$winning = {the function that I'm missing}
I want to find the string that accompanies the highest value variable and then use it in a switch case, for example:
switch ($winning) {
case "Var_One":
echo "This variable is the highest value.";
break;
case "Var_Two":
echo "This variable is the highest value.";
break;
case "Var_Three":
echo "This variable is the highest value.";
break;
default:
echo "Values are tied.";
}
I've tried using a regex solution which didn't work and strpos does NOT do what I need.
Any help is appreciated.
ANSWER:
function getMaxValue(array $list) {
$result = [];
foreach($list as $k => $v) {
if(!isset($result["value"]) || $result["value"] < $v) {
$result = [
"value" => $v,
"key" => $k,
];
}
}
return $result;
}
$winning = ["Var_One" => $var1, "Var_Two" => $var2, "Var_Three" => $var3];
$winning = getMaxValue($winning);
if(strpos($winning,'Var_One') !== false) {
echo "Var_One is currently winning by ".$var1."!";
} else if(strpos($winning,'Var_Two') !== false) {
echo "Var_Two is currently winning by ".$var2."!";
} else if(strpos($winning,'Var_Three') !== false) {
echo "Var_Three is currently winning by ".$var3."!";
} else {
echo "Tie.";
}
I think you might be looking for something like this:
function getMaxValue(array $list)
{
$result = [];
foreach ($list as $k => $v) {
if (!isset($result["value"]) || $result["value"] < $v) {
$result = [
"value" => $v,
"key" => $k,
];
}
}
return $result;
}
Test:
$list = ["one" => 2, "two" => 0, "three" => 5, "four" => 4];
var_dump(getMaxValue($list));
Result:
array(2) {
["value"]=>
int(5)
["key"]=>
string(5) "three"
}
$winning = max(array_map("intval", array($var1."Var_One", $var2."Var_Two", $var3."Var_Tree", $var4."Var_Four")));

PHP: How to get values from array using clause?

Hi all I have an array
$data = array("https://lh6.googleusercontent.com/-pXObolgHAdo/UbBLHGz1R6I/AAAAAAAAAbg/aAkGHbXQ6WU/w958-h715-no/111.jpg",
"https://lh4.googleusercontent.com/-F_ngXcmSdxY/UbBLypozWvI/AAAAAAAAAew/juDGaqNUiSc/w958-h715-no/411.jpg",
"https://lh6.googleusercontent.com/-dxOkxkoZd0k/Ua3jQFu2WqI/AAAAAAAAAQc/eYX-u6mtF3k/w958-h715-no/113.jpg",
"https://lh5.googleusercontent.com/-8XTn3y4s8IY/Ua3jTOTRmxI/AAAAAAAAAQw/6qQA7xtagEo/w958-h715-no/121.jpg");
How can I get specific data from the array using a clause?
eg. I want to pull a data from the array with 121.jpg.
Thanks!
You can loop the array and check the value:
while (list($key, $value) = each ($data)) {
if(strpos($value, '121.jpg') !== false)
{
var_dump($value);
}
}
May be you mean Closure ? What if there are multiple images with the same name ?
function get_image_url($name, array $images) {
$image_url = array_filter($images, function($value) use ($name) {
return (preg_replace('/^(.*\/)/', '', $value) == $name);
});
if (0 == sizeof($image_url)) {
return false;
} elseif (1 == sizeof($image_url)) {
return reset($image_url);
}
return $image_url;
}
Example:
$images = array(
"https://lh6.googleusercontent.com/-pXObolgHAdo/UbBLHGz1R6I/AAAAAAAAAbg/aAkGHbXQ6WU/w958-h715-no/111.jpg",
"https://lh4.googleusercontent.com/-F_ngXcmSdxY/UbBLypozWvI/AAAAAAAAAew/juDGaqNUiSc/w958-h715-no/411.jpg",
"https://lh6.googleusercontent.com/-dxOkxkoZd0k/Ua3jQFu2WqI/AAAAAAAAAQc/eYX-u6mtF3k/w958-h715-no/113.jpg",
"https://lh5.googleusercontent.com/-8XTn3y4s8IY/Ua3jTOTRmxI/AAAAAAAAAQw/6qQA7xtagEo/w958-h715-no/121.jpg",
"121.jpg"
);
var_dump(get_image_url('111.jpg', $images));
// string(103) "https://lh6.googleusercontent.com/-pXObolgHAdo/UbBLHGz1R6I/AAAAAAAAAbg/aAkGHbXQ6WU/w958-h715-no/111.jpg"
var_dump(get_image_url('121.jpg', $images));
// array(2) {
// [3] =>
// string(103) "https://lh5.googleusercontent.com/-8XTn3y4s8IY/Ua3jTOTRmxI/AAAAAAAAAQw/6qQA7xtagEo/w958-h715-no/121.jpg"
// [4] =>
// string(7) "121.jpg"
// }
var_dump(get_image_url('invalid.jpg', $images));
// bool(false)

search a php array for partial string match [duplicate]

This question already has answers here:
Filter multidimensional array based on partial match of search value
(3 answers)
Native function to filter array by prefix
(6 answers)
Closed 1 year ago.
I have an array and I'd like to search for the string 'green'. So in this case it should return the $arr[2]
$arr = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red');
is there any predefined function like in_array() that does the job rather than looping through it and compare each values?
For a partial match you can iterate the array and use a string search function like strpos().
function array_search_partial($arr, $keyword) {
foreach($arr as $index => $string) {
if (strpos($string, $keyword) !== FALSE)
return $index;
}
}
For an exact match, use in_array()
in_array('green', $arr)
You can use preg_grep function of php. It's supported in PHP >= 4.0.5.
$array = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red');
$m_array = preg_grep('/^green\s.*/', $array);
$m_array contains matched elements of array.
There are several ways...
$arr = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red');
Search the array with a loop:
$results = array();
foreach ($arr as $value) {
if (strpos($value, 'green') !== false) { $results[] = $value; }
}
if( empty($results) ) { echo 'No matches found.'; }
else { echo "'green' was found in: " . implode('; ', $results); }
Use array_filter():
$results = array_filter($arr, function($value) {
return strpos($value, 'green') !== false;
});
In order to use Closures with other arguments there is the use-keyword. So you can abstract it and wrap it into a function:
function find_string_in_array ($arr, $string) {
return array_filter($arr, function($value) use ($string) {
return strpos($value, $string) !== false;
});
}
$results = find_string_in_array ($arr, 'green');
if( empty($results) ) { echo 'No matches found.'; }
else { echo "'green' was found in: " . implode('; ', $results); }
Here's a working example: http://codepad.viper-7.com/xZtnN7
PHP 5.3+
array_walk($arr, function($item, $key) {
if(strpos($item, 'green') !== false) {
echo 'Found in: ' . $item . ', with key: ' . $key;
}
});
for search with like as sql with '%needle%' you can try with
$input = preg_quote('gree', '~'); // don't forget to quote input string!
$data = array(
1 => 'orange',
2 => 'green string',
3 => 'green',
4 => 'red',
5 => 'black'
);
$result = preg_filter('~' . $input . '~', null, $data);
and result is
{
"2": " string",
"3": ""
}
function check($string)
{
foreach($arr as $a) {
if(strpos($a,$string) !== false) {
return true;
}
}
return false;
}
A quick search for a phrase in the entire array might be something like this:
if (preg_match("/search/is", var_export($arr, true))) {
// match
}
function findStr($arr, $str)
{
foreach ($arr as &$s)
{
if(strpos($s, $str) !== false)
return $s;
}
return "";
}
You can change the return value to the corresponding index number with a little modification if you want, but since you said "...return the $arr[2]" I wrote it to return the value instead.
In order to find out if UTF-8 case-insensitive substring is present in array, I found that this method would be much faster than using mb_strtolower or mb_convert_case:
Implode the array into a string: $imploded=implode(" ", $myarray);.
Convert imploded string to lowercase using custom function:
$lowercased_imploded = to_lower_case($imploded);
function to_lower_case($str)
{
$from_array=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","Ä","Ö","Ü","Õ","Ž","Š"];
$to_array=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","ä","ö","ü","õ","ž","š"];
foreach($from_array as $key=>$val){$str=str_replace($val, $to_array[$key], $str);}
return $str;
}
Search for match using ordinary strpos: if(strpos($lowercased_imploded, "substring_to_find")!==false){do something}
This is a function for normal or multidimensional arrays.
Case in-sensitive
Works for normal arrays and multidimentional
Works when finding full or partial stings
Here's the code (version 1):
function array_find($needle, array $haystack, $column = null) {
if(is_array($haystack[0]) === true) { // check for multidimentional array
foreach (array_column($haystack, $column) as $key => $value) {
if (strpos(strtolower($value), strtolower($needle)) !== false) {
return $key;
}
}
} else {
foreach ($haystack as $key => $value) { // for normal array
if (strpos(strtolower($value), strtolower($needle)) !== false) {
return $key;
}
}
}
return false;
}
Here is an example:
$multiArray = array(
0 => array(
'name' => 'kevin',
'hobbies' => 'Football / Cricket'),
1 => array(
'name' => 'tom',
'hobbies' => 'tennis'),
2 => array(
'name' => 'alex',
'hobbies' => 'Golf, Softball')
);
$singleArray = array(
0 => 'Tennis',
1 => 'Cricket',
);
echo "key is - ". array_find('cricket', $singleArray); // returns - key is - 1
echo "key is - ". array_find('cricket', $multiArray, 'hobbies'); // returns - key is - 0
For multidimensional arrays only - $column relates to the name of the key inside each array.
If the $needle appeared more than once, I suggest adding onto this to add each key to an array.
Here is an example if you are expecting multiple matches (version 2):
function array_find($needle, array $haystack, $column = null) {
$keyArray = array();
if(is_array($haystack[0]) === true) { // for multidimentional array
foreach (array_column($haystack, $column) as $key => $value) {
if (strpos(strtolower($value), strtolower($needle)) !== false) {
$keyArray[] = $key;
}
}
} else {
foreach ($haystack as $key => $value) { // for normal array
if (strpos(strtolower($value), strtolower($needle)) !== false) {
$keyArray[] = $key;
}
}
}
if(empty($keyArray)) {
return false;
}
if(count($keyArray) == 1) {
return $keyArray[0];
} else {
return $keyArray;
}
}
This returns the key if it has just one match, but if there are multiple matches for the $needle inside any of the $column's then it will return an array of the matching keys.
Hope this helps :)

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;
}

Categories