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.
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
Im looking for a way to remove empty elements from an array.
Im aware of array_filter() which removes all empty values.
The thing is that i consider a string containing nothing but spaces, tabs and newlines also to be empty.
So what is best used in this case?
Use trim() in callback for array_filter:
$array = array_filter($array, function ($v) { return (bool)trim($v); });
Or shorter version (with implicit type-casting):
$array = array_filter($array, 'trim');
php empty()
bool empty ( mixed $var )
Determine whether a variable is considered to be empty. A variable is
considered empty if it does not exist or if its value equals FALSE.
empty() does not generate a warning if the variable does not exist.
Something like should do:
foreach($array as $key => $stuff)
{
if(empty(stuff))
{
unset($array[$key]);
}
}
$array = array_values($array );// to reinstate the numerical indexes.
I know this may be late to answer but it is for those who may have interest in other ways to solve this. It is my own way of doing it.
function my_array_filter($my_array)
{
$final_array = array();
foreach ( $my_array as $my_arr )
{
//check if array element is not empty
if (!empty($my_arr)) $final_array[] = $my_arr;
}
//remove duplicate elements
return array_unique( $final_array );
}
Hope someone finds this useful.
My aim is to find out what the operator is, and where it was in the original $operatorArray (which contains the various operators such as "+", "-" etc... )
So I have managed to check when $operator matches with another operator in my existing $operatorArray, however I need to know where in $operatorArray it is found.
foreach ($_SESSION['explodedQ'] as $operator){ //search through the user input for the operator.
if (in_array("$operator", $operatorArray)) { //if the operator that we found is in the array, then tell us what it is
print_r("$operator"); //prints the operator found
print_r("$positionNumber"); //prints where the operator is
} //if operator
else{
$positionNumber++; //The variable which keeps count on where the array is searching.
}
I've tried Google/Stack searching, but the thing is, I don't actually know what to Google search. I've searched for things like "find index from in_array" etc... and I can't see how to do it. If you could provide me with a simple way to understand how to achieve this, I would be greatful. Thanks for your time.
array_search will do what you are looking for
Taken straight from the PHP manual:
array_search() - Searches the array for a given value and returns the corresponding key if successful
If you're searching a non-associative array, it returns the corresponding key, which is the index you're looking for. For non-consecutively indexed arrays (i.e. array(1 => 'Foo', 3 => 'Bar', ...)) you can use the result of array_values() and search in it.
You might want to give this a try
foreach($_SESSION['explodedQ'] as $index => $operator) { /* your stuff */ }
That way you can print the $index as soon as your in_array() hits the right $operator.
i think you need array_search()
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
Use:
$key = array_search($operator, $array);
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