How to get the position of the string in an array - php

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

Related

Compare All strings in a array to all strings in another array, PHP

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

Getting the numeric value of an array after using in_array

When using:
if (in_array("boots", $products)) {
echo "Boots found";
}
Lets say this comes back as True, then how can I find the numeric value of where "boots" is in my $products array?
You can use the array_search function:
$key = array_search('boots', $products);
The best part is, you can use array_search instead of in_array, because it returns FALSE if the needle can't be found in the haystack.

how to search an array in php?

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>';

Search an array for a matching string

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.

How to find a string in an array in PHP?

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";
}
}

Categories