I am trying to check for values in array and if value found increment it. I've tried to do it as shown in code below, but not successful.
$productdas=array("DAS","DayEnd","DAAS");
if (strpos(serialize($row['pirority']),"P1")!==false &&
strpos(serialize($row['product']),'$productdas')!==false)
{
$dasp1++;
}
I'll be grateful for any help.
Regards.
You would need to write an strpos() variant that accepts an array as $needle; for example:
function strpos_array($haystack, array $needles)
{
foreach ($needles as $needle) {
if (($pos = strpos($haystack, $needle)) !== false) {
return $pos;
}
}
return false;
}
if (strpos_array(serialize($row['product']), $productdas)!==false) { ... }
It's also possible to implement this using preg_match().
I'm assuming you're trying to search the given string for any of the values in $productas array and find the number of total occurrences. This can be done with substr_count():
$productdas = array("DAS","DayEnd","DAAS");
$count = 0;
foreach ($productdas as $needle) {
$count += substr_count($row['pirority'], $needle);
}
echo $count;
If $row['pirority'] is DASfooDayEndDAAShelloDAS, then the count would be 4.
Demo
Related
I need one help. I need to check that string is present inside array or not and also it should search letter wise using PHP. I am explaining my code below.
$resultArr=array("9937229853","9937229856","9937229875");
$searchValue="+919937229853";
Here I need to check that some of the value from $searchValue is present inside in array or not. I am doing like below but its not giving me the proper result.
$searchValue="+919937229853";
$resultArr=array("9937229853","9937229856","9937229875");
if(!in_array($searchValue, $resultArr))
{
$flag=1;
}else{
$flag=0;
}
echo $flag;
As per my requirement here result should print 1 because some value from $searchValue also present in that array but the echo result is coming 0.Please help me.
$searchValue="+919937229853";
$resultArr=array("9937229853","9937229856","9937229875");
foreach($resultArr as $value)
{
if(strpos($value,$searchValue) || strpos($searchValue,$value) || $searchValue==$value)
{
$flag = 1;
break;
}
else
$flag=0;
}
echo $flag;
I think this will do what you are looking for. in_array() method search string in array but for the exact string. strpos can search substring in long string and return the offset number or the index of substring in the long string.
you can try code like below.
if(!in_array(substr($searchValue,-10), $resultArr))
$searchValue="+919937229853";
$searchValue = str_replace("+91","",$searchValue);
$resultArr=array("9937229853","9937229856","9937229875");
if(in_array($searchValue, $resultArr))
{
$flag=1;
}else{
$flag=0;
}
echo $flag;
User str_replace function replace first three charater from string
$flag=0;
for($i=0;$i<strcmp($searchValue);$i++){
for($j=0;$j<strcmp($searchValue);$j++){
$part=substr($searchValue,$i,$j)
array_filter($resultArr, function($el) use ($part) {
if ( strpos($el, $part) !== false ){
$flag=1;
}
});
}
}
The function below will return true if either
your $searchValue is in the array (in_array), or
if any item of the array is a substring of $searchValue
in other words: If part of $searchValue is in the array.
This is the code and how you call it:
function search($needle, $haystack) {
// is $needle contained in the array as it is?
if (in_array($needle, $haystack))
return true;
// Is any part of $needle part of the array?
foreach ($haystack as $value) {
if (strpos($needle, $value) !== FALSE)
return true;
}
return false;
}
$resultArr = array("9937229853", "9937229856", "9937229875");
$searchValue = "+919937229853";
$result = search($searchValue, $resultArr);
var_dump($result);
How can I check if a string contains a member of an array, and return the index (integer) of the relevant member?
Let's say my string is this :
$string1 = "stackoverflow.com";
$string2 = "superuser.com";
$r = array("queue" , "stack" , "heap");
get_index($string1 , $r); // returns 1
get_index($string2 , $r); // returns -1 since string2 does not contain any element of array
How can I write this function in an elegant (short) and efficient way ?
I found a function (expression ? ) that checks if the string contains a member of an array :
(0 < count(array_intersect(array_map('strtolower', explode(' ', $string)), $array)))
but this is a boolean. does the count() function return what I want in this statement ?
Thanks for any help !
function get_index($str, $arr){
foreach($arr as $key => $val){
if(strpos($str, $val) !== false)
return $key;
}
return -1;
}
Demo: https://eval.in/95398
This will find the number of matching elements in your array, if you want all matching keys, use the commented lines instead:
function findMatchingItems($needle, $haystack){
$foundItems = 0; // start counter
// $foundItems = array(); // start array to save ALL keys
foreach($haystack as $key=>$value){ // start to loop through all items
if( strpos($value, $needle)!==false){
++$foundItems; // if found, increase counter
// $foundItems[] = $key; // Add the key to the array
}
}
return $foundItems; // return found items
}
findMatchingItems($string1 , $r);
findMatchingItems($string2 , $r);
If you want to return all matching keys, just change $foundItems to an array and add the keys in the if-statement (switch to the commented lines).
If you only want to know if something matches or not
function findMatchingItems($needle, $haystack){
if( strpos($value, $needle)!==false){
return true;
break; // <- This is important. This stops the loop, saving time ;)
}
return false;// failsave, if no true is returned, this will return
}
I would do a function like this:
function getIndex($string, $array) {
$index = -1;
$i = 0;
foreach($array as $array_elem) {
if(str_pos($array_elem, $string) !== false) {
$index = $i;
}
$i++;
}
return $index;
}
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
I am trying to write a piece of code that searches one column of 2-D array values and returns the key when it finds it. Right now I have two functions, one to find a value and return a boolean true or false and another (not working) to return the key. I would like to merge the two in the sense of preserving the recursive nature of the finding function but returning a key. I cannot think how to do both in one function, but working key finder would be much appreciated.
Thanks
function in_array_r($needle, $haystack, $strict = true) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
function loopAndFind($array, $index, $search){
$returnArray = array();
foreach($array as $k=>$v){
if($v[$index] == $search){
$returnArray[] = $k;
}
}
return $returnArray;
}`
Sorry, I meant to add an example. For instance:
Array [0]{
[0]=hello
[1]=6
}
[1]
{
[0]=world
[1]=4
}
and I want to search the array by the [x][0] index to check each string of words for the search term. If found, it should give back the index/key in the main array like "world" returns 1
This works:
$array = array(array('hello', 6), array('world', 4));
$searchTerm = 'world';
foreach ($array as $childKey => $childArray) {
if ($childArray['0'] == $searchTerm) {
echo $childKey; //Your Result
}
}
You already have all you need in your first function. PHP does the rest:
$findings = array_map('in_array_r', $haystack);
$findings = array_filter($findings); # remove all not found
var_dump(array_keys($findings)); # the keys you look for
I have a function that takes a string (the haystack) and an array of strings (the needles) and returns true if at least one needle is a substring of the haystack. It didn't take much time or effort to write it, but I'm wondering if there's a PHP function that already does this.
function strstr_array_needle($haystack, $arrayNeedles){
foreach($arrayNeedles as $needle){
if(strstr($haystack, $needle)) return true;
}
return false;
}
just a suggestion...
function array_strpos($haystack, $needles)
{
foreach($needles as $needle)
if(strpos($haystack, $needle) !== false) return true;
return false;
}
I think the closest function would be array_walk_recursive(), but that requires a callback. So using it would probably be more complicated than what you already have.
I'm not exactly sure what you're wanting to do but I think in_array() could help you do what you're looking for.
$needleArray = array(1, 2, 3); // the values we want to get from
$outputArray = array( ... ); // the values to search for
foreach ($outputArray as $value) {
if (in_array($value, $needleArray)) {
// do what you want to do...the $value exists in $needleArray
}
}
If you are just trying to determine which needles exist in the haystack, I suggest the array_intersect function.
Documentation from the PHP.net website
<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
?>
The above example will output:
Array
(
[a] => green
[0] => red
)
Basically, this will result in an array that shows all values that appear in both arrays. In your case, your code is returning true if any needle is found. The following code will do this using the array_intersect function, though if this is any simpler than Charles answer is debatable.
if(sizeof(array_intersect($hackstack, $arrayNeedles)) > 0)
return true;
else
return false;
Again, I am not sure exactly what your code is trying to do, other than return true if any needle exists. If you can provide some context on what you want to achieve, there may be a better way.
Hope this helps.
There's no single function that behaves as strstr_array_needle (the name is misleading; I'd expect it to return a substring of $haystack). There are other functions that could be used instead of a loop, but they don't have benefits and take more time. For example:
# iterates over entire array, though stops checking once a match is found
array_reduce($needles,
function($found, $needle) use ($haystack) {
return $found || (strpos($haystack, $needle) !== false);
},
false);
# iterates over entire array and checks each needle, even if one is already found
(bool)array_filter($needles,
function($needle) use ($haystack) {
return strpos($haystack, $needle) !== false;
});
Here is a tested and working function:
<?php
function strpos_array($haystack, $needles, $offset = 0) {
if (is_array($needles)) {
foreach ($needles as $needle) {
$pos = strpos_array($haystack, $needle);
if ($pos !== false) {
return $pos;
}
}
return false;
} else {
return strpos($haystack, $needles, $offset);
}
}