Getting the numeric value of an array after using in_array - php

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.

Related

Remove array element by checking a value php

I have an array as follows
[0=>['classId'=>2,'Name'=>'John'],1=>['classId'=>3,'Name'=>'Doe'],2=>['classId'=>4,'Name'=>'Stayne']]
I need to remove the elements with classId 2 or 4 from array and the expected result should be
[0=>['classId'=>3,'Name'=>'Doe']]
How will i achieve this without using a loop.Hope someone can help
You can use array_filter in conjunction with in_array.
$array = [0=>['classId'=>2,'Name'=>'John'],1=>['classId'=>3,'Name'=>'Doe'],2=>['classId'=>4,'Name'=>'Stayne']];
var_dump(
array_filter($array, function($item){return !in_array($item["classId"], [2,4]);})
);
Explanation
array_filter
Removes elements from the array if the call-back function returns false.
in_array
Searches an array for a value; returns boolean true/false if the value is (not)found.
Try this:
foreach array as $k => $v{
if ($v['classId'] == 2){
unset(array[$k]);
}
}
I just saw your edit, you could use array_filter like so:
function class_filter($arr){
return ($arr['classId'] == "whatever");
}
array_filter($arr, "class_filter");
Note: you'll still need to loop through a multi-dimensional array I believe.

How to get the position of the string in an array

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

PHP Array Search Returns Empty Key

I'm trying to use array_search to find the key of a value in an array, I have the following simple code:
$current_user_existing_shopping_bag_string = '1446784/-/3/-/£797.00(_)902982/-/4/-/£148.80(_) ';
$current_user_existing_shopping_bag_array = explode('(_)', $current_user_existing_shopping_bag_string);
$key = array_search($current_user_existing_shopping_bag_array, '902982');
echo $key;
However I have no idea why this doesn't return the key of the value in the array, it should though. I've been trying various solutions for hours now and still no luck.
Anybody able to give me a pointer why this doesn't return the key for the value in the array?
Thanks
It is because array_search compares strings using === operator, not regex or strpos of any kind.
You search for 902982 but string is 902982/-/4/-/£148.80, and therefore they are not equal in any way.
For what you want to achieve, you can use preg_grep:
$result = preg_grep('/' . preg_quote($search) . '/', $current_user_existing_shopping_bag_array);
Then you can get the keys you need from the resulting array.

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