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>';
Related
I want to know why array_search() is not able to get the position of the string in the following array
MY Code
$row1['infopropiedades'] ="Dirección<>#Fotos<>SALTEST.ANUNCIO.IMAGENES.IMAGEN.IMAGEN_URL#Fotos Description<>SALTEST.ANUNCIO.DESCRIPCION#Map<>#Youtube URL<>#Titulo<>SALTEST.ANUNCIO.TITULO#Descripción<>SALTEST.ANUNCIO.DESCRIPCION#Detalles específicos<>#Telefono<>SALTEST.ANUNCIO.TELEFONO#Celular<>SALTEST.ANUNCIO.TELEFONO#Terreno<>SALTEST.ANUNCIO.TERRENO#Construcción<>SALTEST.ANUNCIO.CONSTRUCCION#Venta<>SALTEST.ANUNCIO.MONEDA#Alquiler<>";
$x= explode("#",$row1['infopropiedades']);
print_r($x);
echo $key = array_search('Fotos Description', $x);
if($key!=0)
{
$v = explode('<>',$x[$key]);
echo $Fotos_Description = $v[1];
}
Thanks in advance
array_search() is looking for the exact string not a partial match. Here is a quick way to get it:
preg_match('/#Fotos Description<>([^#]+)#/', $row1['infopropiedades'], $v);
echo $Fotos_Description = $v[1];
preg_grep was made for searching arrays and will return the results in an array. A combination of key() and preg_grep() will return the key you are looking for.
echo $key = key(preg_grep("/^Fotos Description.*/", $x));
As others pointed out, array_search only matches if the value is equal.
Since your needle is only a part of the whole haystack that each array element contains, array_search won't work. You can loop through all the values and find what you are looking for
foreach($x as $key=>$haystack)
{
if(stristr($haystack,'Fotos Description')!==FALSE)
{
$v = explode('<>',$haystack);
echo $Fotos_Description = $v[1];
}
}
Fiddle
Because array_search just searches for an exact match. So you have to iterate over the whole array and check if the value has this string
or you could use array_filter with a custom callback function for example
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.
this is the output of my array
[["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"]]
but I would like this to look like
[1,1,1,1,1,1,1]
how would this be achieved in php, it seems everything I do gets put into an object in the array, when I don't want that. I tried using array_values and it succeeded in returning the values only, since I did have keys originally, but this is still not the completely desired outcome
$yourArray = [["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"]];
use following code in PHP 5.3+
$newArray = array_map(function($v) {
return (int)$v[0];
}, $yourArray);
OR use following code in other PHP version
function covertArray($v) {
return (int)$v[0];
}
$newArray = array_map('covertArray', $yourArray)
You could always do a simple loop...
$newArray = array();
// Assuming $myArray contains your multidimensional array
foreach($myArray as $value)
{
$newArray[] = $value[0];
}
You could beef it up a little and avoid bad indexes by doing:
if( isset($value[0]) ) {
$newArray[] = $value[0];
}
Or just use one of the many array functions to get the value such as array_pop(), array_slice(), end(), etc.
I am looking for away to check if a string exists as an array value in an array is that possible and how would I do it with PHP?
If you simply want to know if it exists, use in_array(), e.g.:
$exists = in_array("needle", $haystack);
If you want to know its corresponding key, use array_search(), e.g.:
$key = array_search("needle", $haystack);
// will return key for found value, or FALSE if not found
You can use PHP's in_array function to see if it exists, or array_search to see where it is.
Example:
$a = array('a'=>'dog', 'b'=>'fish');
in_array('dog', $a); //true
in_array('cat', $a); //false
array_search('dog', $a); //'a'
array_search('cat', $a); //false
Php inArray()
Incidentally, although you probably should use either in_array or array_search like these fine gentlemen suggest, just so you know how to do a manual search in case you ever need to do one, you can also do this:
<?php
// $arr is the array to be searched, $needle the string to find.
// $found is true if the string is found, false otherwise.
$found = false;
foreach($arr as $key => $value) {
if($value == $needle) {
$found = true;
break;
}
}
?>
I know it seems silly to do a manual search to find a string - and it is - but you may one day wish to do more complicated things with arrays, so it's good to know how to actually get at each $key-$value pair.
Here you go:
http://www.php.net/manual/en/function.array-search.php
The array_search function does exactly what you want.
$index = array_search("string to search for", $array);
Say we have this array:
<?php
$array = array(
1 => 'foo',
2 => 'bar',
3 => 'baz',
);
?>
If you want to check if the element 'foo' is in the array, you would do this
<?php
if(in_array('foo', $array)) {
// in array...
}else{
// not in array...
}
?>
If you want to get the array index of 'foo', you would do this:
<?php
$key = array_search('foo', $array);
?>
Also, a simple rule for the order of the arguments in these functions is: "needle, then haystack"; what you're looking for should be first, and what you're looking in second.
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";
}
}