Remove if array contains string from another array - php

So the idea is to remove from one array a list of numbers of other array, but it's only removing the first one, any help to solve this will be appreciated.
$my_array = array("Sandra Loor,593984076233","Adrian,593998016010","Lucas,593999843424");
function myFilter($string) {
$to_remove = array("593984076233","593998016010");
foreach($to_remove as $remove) {
return strpos($string, $remove) === false;
}
}
$newArray = array_filter($my_array, 'myFilter');
foreach ($newArray as $val){
echo $val.'<br>';
}

The problem is that your filter will always return from the first iteration of the loop.
This instead will return false if it finds the entry and at the end of the loop will return true (i.e. not found at all)...
function myFilter($string) {
$to_remove = array("593984076233","593998016010");
foreach($to_remove as $remove) {
if ( strpos($string, $remove) !== false )
return false;
}
return true;
}

Another method is to use preg_grep to search the array for the items you want to remove, then use array_diff to remove them.
$my_array = array("Sandra Loor,593984076233","Adrian,593998016010","Lucas,593999843424");
$to_remove = array("593984076233","593998016010");
$to_remove = "/" . implode("|", $to_remove) . "/";
$match = preg_grep($to_remove, $my_array);
$filtered = array_diff($my_array, $match);
var_dump($filtered);
// Lucas,593999843424
https://3v4l.org/PZ4I6
You can also bunch it up to a one liner like this:
$my_array = array("Sandra Loor,593984076233","Adrian,593998016010","Lucas,593999843424");
$to_remove = array("593984076233","593998016010");
$filtered = array_diff($my_array, preg_grep("/" . implode("|", $to_remove) . "/", $my_array));
var_dump($filtered);

Related

I'm duplicating my strpos keyword check but I don't want to

I am pulling multiple values ($arr) from list of keywords ($keywords). Later I'm using strpos to check if that keyword existis in a document.
I could just duplicate the whole code and add every $arr manually one by one, like: strpos($element,$arr[0]); strpos($element,$arr[1]); strpos($element,$arr[2]);.
Can anyone help me set it up so that I don't have to do it the long way. Lets say I need a total of 20 $arr checks. That would be $arr[0] to $arr[19].
<?php
$str= "$keywords";
$arr=explode(",",$str);
// print_r($arr);
$data = file($_SERVER['DOCUMENT_ROOT'].'/posts.txt');
$data=str_replace(array('<', '>', '\\', '/', '='), "", $data);
foreach($data as $element)
{
$element = trim($element);
$check_keyword = strpos($element,$arr[0]);
if ($check_keyword !== false) {
$pieces = explode("|", $element);
echo "
" . $pieces[0] . "
<a href=/blog/" . $pieces[2] . "/" . $pieces[3] . "/ ><b><font color=#21b5ec>" . $pieces[4] . "</font></b></a> <br>
";
}
else {
echo "";
}
}
?>
If you want to check every value in $arr against $element then the easiest way to do it is with array_reduce.
If you want to test whether every value in $arr is in $element, you can use this:
$check_keyword = array_reduce($arr, function ($carry, $item) use($element) {
return $carry && (strpos($element, $item) !== false);
}, true);
If you only want to check if any value in $arr is in $element, you can use this:
$check_keyword = array_reduce($arr, function ($carry, $item) use($element) {
return $carry || (strpos($element, $item) !== false);
}, false);

PHP array with url values to new array with combined values

I have tried for a long time but couldn't find a way to merge an array in to a new one.
Mostly I get lost in looping and matching.;(
I would like to recieve a php 5 method that can do the following:
Example 1
Lets say there is an array with url's like:
Array(
'a',
'a/b/c',
'a/b/c/d/e',
'a/y',
'b/z',
'b/z/q/',
)
Every last folder of the url's is the folder where a user has the right to view.
I would like to send the array to a method that returns a new array like:
Array[](
'a/c/e'
'a/y'
'z/q'
)
The method has combined some elements of the origninal array into one element.
This because there is a match in allowed ending folders.
Example 2
Array(
'projects/projectA/books'
'projects/projectA/books/cooking/book1'
'projects/projectA/walls/wall'
'projects/projectX/walls/wall'
'projects/projectZ/'
'projects/projectZ/Wood/Cheese/Bacon'
)
I would like to get a an array like:
Array[](
'books/book1'
'wall'
'wall'
'projectZ/Bacon'
)
Then it would be great (specialy in case of the 'wall' values) to have some references to the full path's of the original array.
Do it like below:-
<?php
$array = Array(
'projects/projectA/books',
'projects/projectA/books/cooking/book1',
'projects/projectA/walls/wall',
'projects/projectX/walls/wall',
'projects/projectZ/',
'projects/projectZ/Wood/Cheese/Bacon'
);// original array
$final_array =array(); // new array variable
foreach($array as $key=>$arr){ // iterate over original array
$exploded_string = end(array_filter(explode('/',$arr))); // get last-value from the url string
foreach($array as $ar){ // iterate again the original array to compare this string withh each array element
$new_exploded_string = end(array_filter(explode('/',$ar))); // get the new-last-values from url string again
if($arr !== $ar && strpos($ar,$exploded_string) !==false){ // if both old and new url strings are not equal and old-last-value find into url string
if($exploded_string == $new_exploded_string ){ // if both new-last-value and old-last-value are equal
$final_array[] = $exploded_string;
}else{
$final_array[] = $exploded_string.'/'.$new_exploded_string ;
}
}
}
}
print_r($final_array);
Output:-https://eval.in/846738
Well, there isn't a single built-in function for this ;)
$items = array(
'projects/projectA/books',
'projects/projectA/books/cooking/book1',
'projects/projectA/walls/wall',
'projects/projectX/walls/wall',
'projects/projectZ/',
'projects/projectZ/Wood/Cheese/Bacon',
'hold/mold/gold/sold/fold',
'hold/mold/gold',
'raja/maza/saza',
'raja/maza',
'mohit/yenky/client/project',
);
echo '$items = ' . nl2br(htmlspecialchars(print_r($items, true))); //Debug
// Sort, so the shorter basePath comes before the longer subPath
usort($items, function($a, $b) {
if (strlen($a) == strlen($b)) {
return 0;
} else {
return strlen($a) > strlen($b) ? 1 : -1;
}
});
$result = array();
while($basePath = array_shift($items)) { // As long as there is a next item
$basePath = rtrim($basePath, '/'); // Right trim extra /
foreach($items as $idx => $subPath) {
if (strpos($subPath, $basePath . '/') === 0) {
// $subPath begins with $basePath
$result[] = preg_replace('#.*/#', '', $basePath) . '/' . preg_replace('#.*/#', '', rtrim($subPath, '/'));
unset($items[$idx]); // Remove item from array, so it won't be matched again
continue 2; // Continue with next while($basePath = array_shift($items))
}
}
// No subPath found, otherwise continue would have called (skipping below code)
$result[] = preg_replace('#.*/#', '', $basePath);
}
echo '$result = ' . nl2br(htmlspecialchars(print_r($result, true))); //Debug
PHPFiddle: http://phpfiddle.org/main/code/ugq9-hy0i
You can avoid using nested loops (and, actually, you should avoid):
sort($array);
$carry = array_shift($array);
$result = [];
$i = 0;
$lastItem = array_reduce($array, function ($carry, $item) use (&$result, &$i) {
$result[$i] = isset($result[$i])
? array_merge($result[$i], [basename($carry)])
: [basename($carry)];
if (strpos($item, $carry) !== 0) {
$i += 1;
}
return $item;
}, $carry);
if (!empty($lastItem)) {
$result[$i] = isset($result[$i])
? array_merge($result[$i], [basename($lastItem)])
: [basename($lastItem)];
}
$result = array_map(function ($item) {
return implode('/', $item);
}, $result);
Here is working demo.
We use array_reduce here to get access to the previously processed item. Also, PHP has function basename, that retrieves the basename. So you can use it and do not reinvent the wheel.

Search for matching partial values in an array [duplicate]

This question already has answers here:
Filter multidimensional array based on partial match of search value
(3 answers)
startsWith() and endsWith() functions in PHP
(34 answers)
Closed 1 year ago.
$target = 285
$array = array("260-315", "285-317", "240-320")
I need to search the array for the value that begins with the $target value. Also, the $target value will not be limited to 3 digits so I'm searching for a match of the digits before the hyphen.
So I want to end up with
$newTarget = 285-317
$finalTarget = 317
Note: I'm only searching for a match of the digits before the hyphen so "200-285" would not be a match
What you asked me in comment(below my answer),for that you can do it like below (My changed answer):-
<?php
$target = 285;
$array = array('260-315', '285-317', '240-320',"200-285");
foreach($array as $key=>$value){
if($target ==explode('-',$value)[0]){
echo $newTarget = $array[$key];
echo PHP_EOL;
echo $finalTarget = explode('-',$array[$key])[1];
}
}
?>
https://eval.in/702862
I can help you filter your array down to members that start with your target.
You can then split the return values to get to your final target.
<?php
$target = '285';
$array = array('260-315', '285-317', '240-320');
$out = array_filter($array, function($val) use ($target) {
return strpos($val, $target) === 0;
});
var_export($out);
Output:
array (
1 => '285-317',
)
<?php
$target = 285;
$arrStack = array(
"260-315",
"285-317",
"240-320",
);
$result = preg_grep('/'.$target.'/',$arrStack);
echo "<pre>"; print_r($result); echo "</pre>";
Something like this could work for you ? array_filter
$target = 285;
$array = array("260-315", "285-317", "240-320");
$newTarget = null;
$finalTarget = null;
$filteredArray = array_filter($array, function($val) use ($target) {
return strpos($val, $target."-") === 0;
});
if(isset($filteredArray[0])){
$newTarget = $filteredArray[0];
$finalTarget = explode($filteredArray[0], "-")[1];
}
Instead of finding what matches, you could exclude what doesn't match with array_filter.
For example:
$target = 285;
$original = array('260-315', '285-317', '240-320');
$final = array_filter($original, function ($value) use ($target) {
// Check if match starts at first character. Have to use absolute check
// because no match returns false
if (stripos($value, $target) === 0) {
return true;
}
return false;
});
The $final array will be a copy of the $original array without the non-matching values.
To output the first digits, you can then loop through your array of matches and get the value before the hyphen:
foreach ($final as $match) {
$parts = explode('-', $match);
if (is_array($parts) && ! empty($parts[0])) {
// Show or do something with value
echo $parts[0];
}
}
Use array_filter:
Example:
$target = '260';
$array = ['260-315', '285-317', '240-320'];
$matches = array_filter($array, function($var) use ($target) { return $target === explode('-', $var)[0]; });
print_r($matches);
Output:
Array
(
[0] => 260-315
)

array values to nested array with PHP

I'm trying to figure out how I can use the values an indexed array as path for another array. I'm exploding a string to an array, and based on all values in that array I'm looking for a value in another array.
Example:
$haystack['my']['string']['is']['nested'] = 'Hello';
$var = 'my#string#is#nested';
$items = explode('#', $var);
// .. echo $haystack[... items..?]
The number of values may differ, so it's not an option to do just $haystack[$items[0][$items[1][$items[2][$items[3]].
Any suggestions?
You can use a loop -
$haystack['my']['string']['is']['nested'] = 'Hello';
$var = 'my#string#is#nested';
$items = explode('#', $var);
$temp = $haystack;
foreach($items as $v) {
$temp = $temp[$v]; // Store the current array value
}
echo $temp;
DEMO
You can use a loop to grab each subsequent nested array. I.e:
$haystack['my']['string']['is']['nested'] = 'Hello';
$var = 'my#string#is#nested';
$items = explode('#', $var);
$val = $haystack;
foreach($items as $key){
$val = $val[$key];
}
echo $val;
Note that this does no checking, you likely want to check that $val[$key] exists.
Example here: http://codepad.org/5ei9xS91
Or you can use a recursive function:
function extractValue($array, $keys)
{
return empty($keys) ? $array : extractValue($array[array_shift($keys)], $keys) ;
}
$haystack = array('my' => array('string' => array('is' => array('nested' => 'hello'))));
echo extractValue($haystack, explode('#', 'my#string#is#nested'));

PHP: find biggest overlap between multiple strings

I have this array:
$array = array('abc123', 'ac123', 'tbc123', '1ac123');
I want to compare each string to each other and find the longest common substring. In the example above the result would be c123.
Update
I've completely misunderstood the question; the aim was to find the biggest overlap between an array of strings:
$array = array('abc123', 'ac123', 'tbc123', '1ac123');
function overlap($a, $b)
{
if (!strlen($b)) {
return '';
}
if (strpos($a, $b) !== false) {
return $b;
}
$left = overlap($a, substr($b, 1));
$right = overlap($a, substr($b, 0, -1));
return strlen($left) > strlen($right) ? $left : $right;
}
$biggest = null;
foreach ($array as $item) {
if ($biggest === null) {
$biggest = $item;
}
if (($biggest = overlap($biggest, $item)) === '') {
break;
}
}
echo "Biggest match = $biggest\n";
I'm not great at recursion, but I believe this should work ;-)
Old answer
I would probably use preg_grep() for that; it returns an array with the matches it found based on your search string:
$matches = preg_grep('/' . preg_quote($find, '/') . '/', $array);
Alternatively, you could use array_filter():
$matches = array_filter($array, function($item) use ($find) {
return strpos($item, $find) !== false;
});
I need to extract the value "c123" like it is the biggest match for all strings in array
I think what you would want to do here is then sort the above output based on string length (i.e. smallest string length first) and then take the first item:
if ($matches) {
usort($matches, function($a, $b) {
return strlen($a) - strlen($b);
});
echo current($matches); // take first one: ac123
}
Let me know if I'm wrong about that.
If you're just after knowing whether $find matches an element exactly:
$matching_keys = array_keys($array, $find, true); // could be empty array
Or:
$matching_key = array_search($find, $array, true); // could be false
Or event:
$have_value = in_array($find, $array, true);
in_array($find, $array);
returns true if it's in the array, but it has to be the exact match, in your case it won't finde 'ac123'.
if you want to see if it contains the string then you need to loop through the array and use a preg_match() or similar
You could use array_filter with a callback.
$output = array_filter ($input, function ($elem) { return false !== strpos ($elem, 'c123'); });
<?php
$array1 = array('abc123', 'ac123', 'tbc123', '1ac123');
if (in_array("c123", $array1)) {
echo "Got c123";
}
?>
You can use in_array as used here http://codepad.org/nOdaajNe
or use can use array_search as used here http://codepad.org/DAC1bVCi
see if it can help you ..
Documentation link : http://php.net/manual/en/function.array-search.php and http://www.php.net/manual/en/function.in-array.php

Categories