I have a PHP array with a parent called "items." In that array, I want to remove all values that do not contain a string (which I'm gonna use regex to find). How would I do this?
foreach($array['items'] as $key=>$value) { // loop through the array
if( !preg_match("/your_regex/", $value) ) {
unset($array['items'][$key]);
}
}
You can try using array_filter.
$items = array(
#some values
);
$regex= '/^[some]+(regex)*$/i';
$items = array_filter($items, function($a) use ($regex){
return preg_match($regex, $a) !== 0;
});
NOTE: This only works in PHP 5.3+. In 5.2, you can do it this way:
function checkStr($a){
$regex= '/^[some]+(regex)*$/i';
return preg_match($regex, $a) !== 0;
}
$items = array(
#some values
);
$items = array_filter($items, 'checkStr');
Related
How i can remove a value from array what is not fully match the letters.
Array code example:
$Array = array(
'Funny',
'funnY',
'Games',
);
How I can unset all values from this array what is 'funny'
I try via unset('funny'); but is not removing the values from array, is removed just if i have 'funny' on array but 'funnY' or 'Funny' not working
Maybe there is some sophisticated solution with array_intersect_key or something which could do this in one line but I assume this approach is more easily read:
function removeCaseInsensitive($array, $toRemove) {
$ret = [];
foreach ($array as $v) {
if (strtolower($v) != strtolower($toRemove))
$ret[] = $v;
}
return $ret;
}
This returns a new array that does not contain any case of $toRemove. If you want to keep the keys than you can do this:
function removeCaseInsensitive($array, $toRemove) {
$keep = [];
foreach ($array as $k => $v) {
if (strtolower($v) != strtolower($toRemove))
$keep[$k] = true;
}
return array_intersect_keys($array, $keep);
}
You can filter out those values with a loose filtering rule:
$array = array_filter($array, function($value) {
return strtolower($value) !== 'funny';
});
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)
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;
}
}
I have this kind of simple array:
$puctures=array('1_noname.jpg','2_new.jpg','1_ok.jpg','3_lets.jpg','1_stack.jpg','1_predlog.jpg','3_loli.jpg');
I want to make new array that i will only have elements thats starts with 1_
Example
$new=array('1_noname.jpg','1_ok.jpg','1_stack.jpg','1_predlog.jpg');
Something like array_pop but how?
See array_filter():
$new = array_filter(
$puctures,
function($a) {return substr($a, 0, 2) == '1_'; }
);
A simple loop will do.
foreach ($pictures as $picture) {
if (substr($picture, 0, 2) == "1_") {
$new[] = $picture;
}
}
Use array_filter() to get your array:
$new = array_filter($puctures, function($item)
{
//here strpos() may be a better option:
return preg_match('/^1_/', $item);
});
This examples uses array_push() & strpos()
$FirstPictures = array();
foreach( $pictures as $pic => $value ) {
if ( strpos( $value, '1_' ) !== 0 ) {
array_push( $FirstPictures, $pic );
}
}
$puctures=array('1_noname.jpg','2_new.jpg','1_ok.jpg','3_lets.jpg','1_stack.jpg','1_predlog.jpg','3_loli.jpg');
$new=array();
foreach($puctures as $value)
{
if(strchr($value,'1'))
$new[]=$value;
}
echo "<pre>"; print_r($new);
This question already has answers here:
Filter multidimensional array based on partial match of search value
(3 answers)
Closed 1 year ago.
$example = array('An example','Another example','Last example');
How can I do a loose search for the word "Last" in the above array?
echo array_search('Last example',$example);
The code above will only echo the value's key if the needle matches everything in the value exactly, which is what I don't want. I want something like this:
echo array_search('Last',$example);
And I want the value's key to echo if the value contains the word "Last".
To find values that match your search criteria, you can use array_filter function:
$example = array('An example','Another example','Last example');
$searchword = 'last';
$matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); });
Now $matches array will contain only elements from your original array that contain word last (case-insensitive).
If you need to find keys of the values that match the criteria, then you need to loop over the array:
$example = array('An example','Another example','One Example','Last example');
$searchword = 'last';
$matches = array();
foreach($example as $k=>$v) {
if(preg_match("/\b$searchword\b/i", $v)) {
$matches[$k] = $v;
}
}
Now array $matches contains key-value pairs from the original array where values contain (case- insensitive) word last.
function customSearch($keyword, $arrayToSearch){
foreach($arrayToSearch as $key => $arrayItem){
if( stristr( $arrayItem, $keyword ) ){
return $key;
}
}
}
$input= array('An example','Another example','Last example');
$needle = 'Last';
$ret = array_keys(array_filter($input, function($var) use ($needle){
return strpos($var, $needle) !== false;
}));
This will give you all the keys whose value contain the needle.
It finds an element's key with first match:
echo key(preg_grep('/\b$searchword\b/i', $example));
And if you need all keys use foreach:
foreach (preg_grep('/\b$searchword\b/i', $example) as $key => $value) {
echo $key;
}
The answer that Aleks G has given is not accurate enough.
$example = array('An example','Another example','One Example','Last example');
$searchword = 'last';
$matches = array();
foreach($example as $k=>$v) {
if(preg_match("/\b$searchword\b/i", $v)) {
$matches[$k] = $v;
}
}
The line
if(preg_match("/\b$searchword\b/i", $v)) {
should be replaced by these ones
$match_result = preg_match("/\b$searchword\b/i", $v);
if( $match_result!== false && $match_result === 1 ) {
Or more simply
if( preg_match("/\b$searchword\b/i", $v) === 1 ) {
In agreement with http://php.net/manual/en/function.preg-match.php
preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.
I do not like regex because as far as I know, they are always slower than a normal string function. So my solution is:
function substr_in_array($needle, array $haystack)
{
foreach($haystack as $value)
{
if(strpos($value, $needle) !== FALSE) return TRUE;
}
return FALSE;
}
I was also looking for a solution to OP's problem and I stumbled upon this question via Google. However, none of these answers did it for me so I came up with something a little different that works well.
$arr = array("YD-100 BLACK", "YD-100 GREEN", "YD-100 RED", "YJ-100 BLACK");
//split model number from color
$model = explode(" ",$arr[0])
//find all values that match the model number
$match_values = array_filter($arr, function($val,$key) use (&$model) { return stristr($val, $model[0]);}, ARRAY_FILTER_USE_BOTH);
//returns
//[0] => YD-100 BLACK
//[1] => YD-100 GREEN
//[2] => YD-100 RED
This will only work with PHP 5.6.0 and above.