I have an array:
$array = array("apple", "banana", "cap", "dog", etc..) up to 80 values.
and a string variable:
$str = "abc";
If I want to check whether this string ($str) exists in the array or not, I use the preg_match function, which is like this:
$isExists = preg_match("/$str/", $array);
if ($isExists) {
echo "It exists";
} else {
echo "It does not exist";
}
Is it the correct way? If the array grows bigger, will it be very slow? Is there any other method? I am trying to scaling down my database traffic.
And if I have two or more strings to compare, how can I do that?
bool in_array ( mixed $needle , array $haystack [, bool $strict ] )
http://php.net/manual/en/function.in-array.php
If you just need an exact match, use in_array($str, $array) - it will be faster.
Another approach would be to use an associative array with your strings as the key, which should be logarithmically faster. Doubt you'll see a huge difference between that and the linear search approach with just 80 elements though.
If you do need a pattern match, then you'll need to loop over the array elements to use preg_match.
You edited the question to ask "what if you want to check for several strings?" - you'll need to loop over those strings, but you can stop as soon as you don't get a match...
$find=array("foo", "bar");
$found=count($find)>0; //ensure found is initialised as false when no terms
foreach($find as $term)
{
if(!in_array($term, $array))
{
$found=false;
break;
}
}
preg_match expects a string input not an array. If you use the method you described you will receive:
Warning: preg_match() expects parameter 2 to be string, array given in LOCATION on line X
You want in_array:
if ( in_array ( $str , $array ) ) {
echo 'It exists';
} else {
echo 'Does not exist';
}
Why not use the built-in function in_array? (http://www.php.net/in_array)
preg_match will only work when looking for a substring in another string. (source)
If you have more than one value you could either test every value separatly:
if (in_array($str1, $array) && in_array($str2, $array) && in_array($str3, $array) /* … */) {
// every string is element of the array
// replace AND operator (`&&`) by OR operator (`||`) to check
// if at least one of the strings is element of the array
}
Or you could do an intersection of both the strings and the array:
$strings = array($str1, $str2, $str3, /* … */);
if (count(array_intersect($strings, $array)) == count($strings)) {
// every string is element of the array
// remove "== count($strings)" to check if at least one of the strings is element
// of the array
}
The function in_array() only detects complete entries if an array element. If you wish to detect a partial string within an array, each element must be inspected.
foreach ($array AS $this_string) {
if (preg_match("/(!)/", $this_string)) {
echo "It exists";
}
}
Related
I've taken a look around but cant seem to find anything that does as needed.
Lets say I have 2 arrays in a function, however they are completely dynamic. So each time this function is run, the arrays are created based on a page that has been submitted.
I need to some how match these arrays and look for any phrase/words that appear in both.
Example: (with only a single element in each array)
Array 1: "This is some sample text that will display on the web"
Array 2: "You could always use some sample text for testing"
So in that example, the 2 arrays have a phrase that appears exactly the same in each: "Sample Text"
So seeing as these arrays are always dynamic I am unable to do anything like Regex because I will never know what words will be in the arrays.
You could find all words in an array of strings like this:
function find_words(array $arr)
{
return array_reduce($arr, function(&$result, $item) {
if (($words = str_word_count($item, 1))) {
return array_merge($result, $words);
}
}, array());
}
To use it, you run the end results through array_intersect:
$a = array('This is some sample text that', 'will display on the web');
$b = array('You could always use some sample text for testing');
$similar = array_intersect(find_words($a), find_words($b));
// ["some", "sample", "text"]
Array_intersect() should do this for you:
http://www.php.net/manual/en/function.array-intersect.php
*array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.*
maybe something like this:
foreach($arr as $v) {
$pos = strpos($v, "sample text");
if($pos !== false) {
// success
}
}
here is the manual:
http://de3.php.net/manual/de/function.strpos.php
Explode the two strings by spaces, and it is a simple case of comparing arrays.
Hi I'm working on a checking a given array for a certain value.
my array looks like
while($row = mysqli_fetch_array($result)){
$positions[] = array( 'pos' => $row['pos'], 'mark' => $row['mark'] );
}
I'm trying to get the info from it with a method like
<?php
if(in_array('1', $positions)){
echo "x";
}
?>
This I know the value '1' is in the array but the x isn't being sent as out put. any suggestions on how to get "1" to be recognized as being in the array?
Edit:
I realize that this is an array inside of an array. is it possible to combine in_array() to say something like:
"is the value '1' inside one of these arrays"
in_array is not recursive. You're checking if 1 is in an array of arrays which doesn't make sense. You'll have to loop over each element and check that way.
$in = false;
foreach ($positions as $pos) {
if (in_array(1, $pos)) {
$in = true;
break;
}
}
in_array only checks the first level. In this case, it only sees a bunch of arrays, no numbers of any kind. Instead, consider looping through the array with foreach, and check if that 1 is where you expect it to be.
That's because $positions is an array of arrays (a multi-dimensional array).
It contains no simple '1'.
Try a foreach-loop instead:
foreach($postions as $value)
if ($value["pos"] == '1')
echo "x ".$value["mark"];
The problem is that 1 isn't actually in the array. It's in one of the array's within the array. You are comparing the value 1 to the value Array which obviously isn't the same.
Something like this should get you started:
foreach ($positions as $position) {
if ($position['pos'] == 1) {
echo "x";
break;
}
}
Your array $positions is recursive, due to the fact that you use $positions[] in your first snippet. in_array is not recursive (see the PHP manual). Therefore, you need a custom function which works with recursive arrays (source):
<?php
function in_arrayr( $needle, $haystack ) {
foreach( $haystack as $v ){
if( $needle == $v )
return true;
elseif( is_array( $v ) )
if( in_arrayr( $needle, $v ) )
return true;
}
return false;
}
?>
Instead of calling in_array() in your script, you should now call in_arrayr().
What i am trying to do is really but i am going into a lot of detail to make sure it is easily understandable.
I have a array that has a few strings in it. I then have another that has few other short strings in it usually one or two words.
I need it so that if my app finds one of the string words in the second array, in one of the first arrays string it will proceed to the next action.
So for example if one of the strings in the first array is "This is PHP Code" and then one of the strings in the second is "PHP" Then it finds a match it proceeds to the next action. I can do this using this code:
for ( $i = 0; $i < count($Array); $i++) {
$Arrays = strpos($Array[$i],$SecondArray[$i]);
if ($Arrays === false) {
echo 'Not Found Array String';
}
else {
echo 'Found Array String';
However this only compares the First Array object at the current index in the loop with the Second Array objects current index in the loop.
I need it to compare all the values in the array, so that it searches every value in the first array for the First Value in the second array, then every value in the First array for the Second value in the second array and so on.
I think i have to do two loops? I tried this but had problems with the array only returning the first value.
If anyone could help it would be appreciated!
Ill mark the correct answer and + 1 any helpful comments!
Thanks!
Maybe the following is a solution:
// loop through array1
foreach($array1 as $line) {
// check if the word is found
$word_found = false;
// explode on every word
$words = explode(" ", $line);
// loop through every word
foreach($words as $word) {
if(in_array($word, $array2)) {
$word_found = true;
break;
}
}
// if the word is found do something
if($word_found) {
echo "There is a match found.";
} else {
echo "No match found."
}
}
Should give you the result you want. I'm absolute sure there is a more efficient way to do this.. but thats for you 2 find out i quess.. good luck
You can first normalize your data and then use PHP's build in array functions to get the intersection between two arrays.
First of all convert each array with those multiple string with multiple words in there into an array only containing all words.
A helpful function to get all words from a string can be str_word_count.
Then compare those two "all words" arrays with each other using array_intersect.
Something like this:
$words1 = array_unique(str_word_count(implode(' ', $Array), 1));
$words2 = array_unique(str_word_count(implode(' ', $SecondArray), 1));
$intersection = array_intersect($words1, $words2);
if(count($intersection))
{
# there is a match!
}
function findUnit($packaging_units, $packaging)
{
foreach ($packaging_units as $packaging_unit) {
if (str_contains(strtoupper($packaging[3]), $packaging_unit)) {
return $packaging_unit;
}
}
}
Here First parameter is array and second one is variable to find
suppose I have an array of names, what I want is that I want to search this particular array against the string or regular expression and then store the found matches in another array. Is this possible ? if yes then please can your give me hint ? I am new to programming.
To offer yet another solution, I would recommend using PHP's internal array_filter to perform the search.
function applyFilter($element){
// test the element and see if it's a match to
// what you're looking for
}
$matches = array_filter($myArray,'applyFilter');
As of PHP 5.3, you can use an anonymous function (same code as above, just declared differently):
$matches = array_filter($myArray, function($element) {
// test the element and see if it's a match to
// what you're looking for
});
what you would need to di is map the array with a callback like so:
array_filter($myarray,"CheckMatches");
function CheckMatches($key,$val)
{
if(preg_match("...",$val,$match))
{
return $match[2];
}
}
This will run the callback for every element in the array!
Updated to array_filter
well in this case you would probably do something along the lines of a foreach loop to iterate through the array to find what you are looking for.
foreach ($array as $value) {
if ($searching_for === $value) {/* You've found what you were looking for, good job! */}
}
If you wish to use a PHP built in method, you can use in_array
$array = array("1", "2", "3");
if (in_array("2", $array)) echo 'Found ya!';
1) Store the strings in array1
2) array2 against you want to match
3) array3 in which you store the matches
$array1 = array("1","6","3");
$array2 = array("1","2","3","4","5","6","7");
foreach($array1 as $key=>$value){
if(in_array($value,$array2))
$array3[] = $value;
}
echo '<pre>';
print_r($array3);
echo '</pre>';
I have an array and in that array I have an array key that looks like, show_me_160 this array key may change a little, so sometimes the page may load and the array key maybe show_me_120, I want to now is possible to just string match the array key up until the last _ so that I can check what the value is after the last underscore?
one solution i can think of:
foreach($myarray as $key=>$value){
if("show_me_" == substr($key,0,8)){
$number = substr($key,strrpos($key,'_'));
// do whatever you need to with $number...
}
}
I ran into a similar problem recently. This is what I came up with:
$value = $my_array[current(preg_grep('/^show_me_/', array_keys($my_array)))];
you would have to iterate over your array to check each key separately, since you don't have the possibility to query the array directly (I'm assuming the array also holds totally unrelated keys, but you can skip the if part if that's not the case):
foreach($array as $k => $v)
{
if (strpos($k, 'show_me_') !== false)
{
$number = substr($k, strrpos($k, '_'));
}
}
However, this sounds like a very strange way of storing data, and if I were you, I'd check if there's not an other way (more efficient) of passing data around in your application ;)
to search for certain string in array keys you can use array_filter(); see docs
// the array you'll search in
$array = ["search_1"=>"value1","search_2"=>"value2","not_search"=>"value3"];
// filter the array and assign the returned array to variable
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($key){
return(strpos($key,'search_') !== false);
},
// flag to let the array_filter(); know that you deal with array keys
ARRAY_FILTER_USE_KEY
);
// print out the returned array
print_r($foo);
if you search in the array values you can use the flag 0 or leave the flag empty
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($value){
return(strpos($value,'value') !== false);
},
// flag to let the array_filter(); know that you deal with array value
0
);
or
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($value){
return(strpos($value,'value') !== false);
}
);
if you search in the array values and array keys you can use the flag ARRAY_FILTER_USE_BOTH
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($value, $key){
return(strpos($key,'search_') !== false or strpos($value,'value') !== false);
},
ARRAY_FILTER_USE_BOTH
);
in case you'll search for both you have to pass 2 arguments to the callback function
You can also use a preg_match based solution:
foreach($array as $str) {
if(preg_match('/^show_me_(\d+)$/',$str,$m)) {
echo "Array element ",$str," matched and number = ",$m[1],"\n";
}
}
filter_array($array,function ($var){return(strpos($var,'searched_word')!==FALSE);},);
return array 'searched_key' => 'value assigned to the key'
foreach($myarray as $key=>$value)
if(count(explode('show_me_',$event_key)) > 1){
//if array key contains show_me_
}
More information (example):
if array key contain 'show_me_'
$example = explode('show_me_','show_me_120');
print_r($example)
Array ( [0] => [1] => 120 )
print_r(count($example))
2
print_r($example[1])
120