check whether a value exist in codeigniter result_array [duplicate] - php
I use in_array() to check whether a value exists in an array like below,
$a = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $a))
{
echo "Got Irix";
}
//print_r($a);
but what about an multidimensional array (below) - how can I check that value whether it exists in the multi-array?
$b = array(array("Mac", "NT"), array("Irix", "Linux"));
print_r($b);
or I shouldn't be using in_array() when comes to the multidimensional array?
in_array() does not work on multidimensional arrays. You could write a recursive function to do that for you:
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
Usage:
$b = array(array("Mac", "NT"), array("Irix", "Linux"));
echo in_array_r("Irix", $b) ? 'found' : 'not found';
If you know which column to search against, you can use array_search() and array_column():
$userdb = Array
(
(0) => Array
(
('uid') => '100',
('name') => 'Sandra Shush',
('url') => 'urlof100'
),
(1) => Array
(
('uid') => '5465',
('name') => 'Stefanie Mcmohn',
('url') => 'urlof5465'
),
(2) => Array
(
('uid') => '40489',
('name') => 'Michael',
('url') => 'urlof40489'
)
);
if(array_search('urlof5465', array_column($userdb, 'url')) !== false) {
echo 'value is in multidim array';
}
else {
echo 'value is not in multidim array';
}
This idea is in the comments section for array_search() on the PHP manual;
This will work too.
function in_array_r($item , $array){
return preg_match('/"'.preg_quote($item, '/').'"/i' , json_encode($array));
}
Usage:
if(in_array_r($item , $array)){
// found!
}
This will do it:
foreach($b as $value)
{
if(in_array("Irix", $value, true))
{
echo "Got Irix";
}
}
in_array only operates on a one dimensional array, so you need to loop over each sub array and run in_array on each.
As others have noted, this will only for for a 2-dimensional array. If you have more nested arrays, a recursive version would be better. See the other answers for examples of that.
$userdb = Array
(
(0) => Array
(
('uid') => '100',
('name') => 'Sandra Shush',
('url') => 'urlof100'
),
(1) => Array
(
('uid') => '5465',
('name') => 'Stefanie Mcmohn',
('url') => 'urlof5465'
),
(2) => Array
(
('uid') => '40489',
('name') => 'Michael',
('url') => 'urlof40489'
)
);
$url_in_array = in_array('urlof5465', array_column($userdb, 'url'));
if($url_in_array) {
echo 'value is in multidim array';
}
else {
echo 'value is not in multidim array';
}
if your array like this
$array = array(
array("name" => "Robert", "Age" => "22", "Place" => "TN"),
array("name" => "Henry", "Age" => "21", "Place" => "TVL")
);
Use this
function in_multiarray($elem, $array,$field)
{
$top = sizeof($array) - 1;
$bottom = 0;
while($bottom <= $top)
{
if($array[$bottom][$field] == $elem)
return true;
else
if(is_array($array[$bottom][$field]))
if(in_multiarray($elem, ($array[$bottom][$field])))
return true;
$bottom++;
}
return false;
}
example : echo in_multiarray("22", $array,"Age");
For Multidimensional Children: in_array('needle', array_column($arr, 'key'))
For One Dimensional Children: in_array('needle', call_user_func_array('array_merge', $arr))
Great function, but it didnt work for me until i added the if($found) { break; } to the elseif
function in_array_r($needle, $haystack) {
$found = false;
foreach ($haystack as $item) {
if ($item === $needle) {
$found = true;
break;
} elseif (is_array($item)) {
$found = in_array_r($needle, $item);
if($found) {
break;
}
}
}
return $found;
}
Since PHP 5.6 there is a better and cleaner solution for the original answer :
With a multidimensional array like this :
$a = array(array("Mac", "NT"), array("Irix", "Linux"))
We can use the splat operator :
return in_array("Irix", array_merge(...$a), true)
If you have string keys like this :
$a = array("a" => array("Mac", "NT"), "b" => array("Irix", "Linux"))
You will have to use array_values in order to avoid the error Cannot unpack array with string keys :
return in_array("Irix", array_merge(...array_values($a)), true)
You could always serialize your multi-dimensional array and do a strpos:
$arr = array(array("Mac", "NT"), array("Irix", "Linux"));
$in_arr = (bool)strpos(serialize($arr),'s:4:"Irix";');
if($in_arr){
echo "Got Irix!";
}
Various docs for things I used:
strpos()
serialize()
Type Juggling or (bool)
I believe you can just use array_key_exists nowadays:
<?php
$a=array("Mac"=>"NT","Irix"=>"Linux");
if (array_key_exists("Mac",$a))
{
echo "Key exists!";
}
else
{
echo "Key does not exist!";
}
?>
The accepted solution (at the time of writing) by jwueller
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
Is perfectly correct but may have unintended behaviuor when doing weak comparison (the parameter $strict = false).
Due to PHP's type juggling when comparing values of different type both
"example" == 0
and
0 == "example"
Evaluates true because "example" is casted to int and turned into 0.
(See Why does PHP consider 0 to be equal to a string?)
If this is not the desired behaviuor it can be convenient to cast numeric values to string before doing a non-strict comparison:
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if( ! $strict && is_string( $needle ) && ( is_float( $item ) || is_int( $item ) ) ) {
$item = (string)$item;
}
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
This is the first function of this type that I found in the php manual for in_array. Functions in the comment sections aren't always the best but if it doesn't do the trick you can look in there too :)
<?php
function in_multiarray($elem, $array)
{
// if the $array is an array or is an object
if( is_array( $array ) || is_object( $array ) )
{
// if $elem is in $array object
if( is_object( $array ) )
{
$temp_array = get_object_vars( $array );
if( in_array( $elem, $temp_array ) )
return TRUE;
}
// if $elem is in $array return true
if( is_array( $array ) && in_array( $elem, $array ) )
return TRUE;
// if $elem isn't in $array, then check foreach element
foreach( $array as $array_element )
{
// if $array_element is an array or is an object call the in_multiarray function to this element
// if in_multiarray returns TRUE, than return is in array, else check next element
if( ( is_array( $array_element ) || is_object( $array_element ) ) && $this->in_multiarray( $elem, $array_element ) )
{
return TRUE;
exit;
}
}
}
// if isn't in array return FALSE
return FALSE;
}
?>
Here is my proposition based on json_encode() solution with :
case insensitive option
returning the count instead of true
anywhere in arrays (keys and values)
If word not found, it still returns 0 equal to false.
function in_array_count($needle, $haystack, $caseSensitive = true) {
if(!$caseSensitive) {
return substr_count(strtoupper(json_encode($haystack)), strtoupper($needle));
}
return substr_count(json_encode($haystack), $needle);
}
Hope it helps.
I was looking for a function that would let me search for both strings and arrays (as needle) in the array (haystack), so I added to the answer by #jwueller.
Here's my code:
/**
* Recursive in_array function
* Searches recursively for needle in an array (haystack).
* Works with both strings and arrays as needle.
* Both needle's and haystack's keys are ignored, only values are compared.
* Note: if needle is an array, all values in needle have to be found for it to
* return true. If one value is not found, false is returned.
* #param mixed $needle The array or string to be found
* #param array $haystack The array to be searched in
* #param boolean $strict Use strict value & type validation (===) or just value
* #return boolean True if in array, false if not.
*/
function in_array_r($needle, $haystack, $strict = false) {
// array wrapper
if (is_array($needle)) {
foreach ($needle as $value) {
if (in_array_r($value, $haystack, $strict) == false) {
// an array value was not found, stop search, return false
return false;
}
}
// if the code reaches this point, all values in array have been found
return true;
}
// string handling
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle)
|| (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
I used this method works for any number of nested and not require hacking
<?php
$blogCategories = [
'programing' => [
'golang',
'php',
'ruby',
'functional' => [
'Erlang',
'Haskell'
]
],
'bd' => [
'mysql',
'sqlite'
]
];
$it = new RecursiveArrayIterator($blogCategories);
foreach (new RecursiveIteratorIterator($it) as $t) {
$found = $t == 'Haskell';
if ($found) {
break;
}
}
Please try:
in_array("irix",array_keys($b))
in_array("Linux",array_keys($b["irix"])
Im not sure about the need, but this might work for your requirement
It works too creating first a new unidimensional Array from the original one.
$arr = array("key1"=>"value1","key2"=>"value2","key3"=>"value3");
foreach ($arr as $row) $vector[] = $row['key1'];
in_array($needle,$vector);
Shorter version, for multidimensional arrays created based on database result sets.
function in_array_r($array, $field, $find){
foreach($array as $item){
if($item[$field] == $find) return true;
}
return false;
}
$is_found = in_array_r($os_list, 'os_version', 'XP');
Will return if the $os_list array contains 'XP' in the os_version field.
what about array_search? seems it quite faster than foreach according to https://gist.github.com/Ocramius/1290076 ..
if( array_search("Irix", $a) === true)
{
echo "Got Irix";
}
I found really small simple solution:
If your array is :
Array
(
[details] => Array
(
[name] => Dhruv
[salary] => 5000
)
[score] => Array
(
[ssc] => 70
[diploma] => 90
[degree] => 70
)
)
then the code will be like:
if(in_array("5000",$array['details'])){
echo "yes found.";
}
else {
echo "no not found";
}
I have found the following solution not very clean code but it works. It is used as an recursive function.
function in_array_multi( $needle, $array, $strict = false ) {
foreach( $array as $value ) { // Loop thorugh all values
// Check if value is aswell an array
if( is_array( $value )) {
// Recursive use of this function
if(in_array_multi( $needle, $value )) {
return true; // Break loop and return true
}
} else {
// Check if value is equal to needle
if( $strict === true ) {
if(strtolower($value) === strtolower($needle)) {
return true; // Break loop and return true
}
}else {
if(strtolower($value) == strtolower($needle)) {
return true; // Break loop and return true
}
}
}
}
return false; // Nothing found, false
}
Many of these searches are usually for finding things in a list of records, as some people have pointed out is really a 2-dimensional array.
This is for a list of records that have a uniform set of keys) such as a list of records grabbed from a database, among other things.
Included are both 'in_array' and 'key_exists' styled functions for this structure for completeness. Both functions return a simple true/false boolean answer.
Example 2-dimensional array of records...
$records array:
[0] => Array
(
[first_name] => Charlie
[last_name] => Brown
)
[1] => Array
(
[first_name] => Fred
[last_name] => Sanford
)
Functions:
function in_multidimensional_array($array, $column_key, $search) {
return in_array($search, array_column($array, $column_key));
}
function multidimensional_array_key_exists($array, $column_key) {
return in_array($column_key, array_keys(array_shift($array)));
}
Tests:
var_dump(in_multidimensional_array($records, 'first_name', 'Charlie')); // true
var_dump(multidimensional_array_key_exists($records, 'first_name')); // true
you can use like this
$result = array_intersect($array1, $array2);
print_r($result);
http://php.net/manual/tr/function.array-intersect.php
Related
Trying to compare a string to an array using strpos but not working [duplicate]
I use in_array() to check whether a value exists in an array like below, $a = array("Mac", "NT", "Irix", "Linux"); if (in_array("Irix", $a)) { echo "Got Irix"; } //print_r($a); but what about an multidimensional array (below) - how can I check that value whether it exists in the multi-array? $b = array(array("Mac", "NT"), array("Irix", "Linux")); print_r($b); or I shouldn't be using in_array() when comes to the multidimensional array?
in_array() does not work on multidimensional arrays. You could write a recursive function to do that for you: function in_array_r($needle, $haystack, $strict = false) { foreach ($haystack as $item) { if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) { return true; } } return false; } Usage: $b = array(array("Mac", "NT"), array("Irix", "Linux")); echo in_array_r("Irix", $b) ? 'found' : 'not found';
If you know which column to search against, you can use array_search() and array_column(): $userdb = Array ( (0) => Array ( ('uid') => '100', ('name') => 'Sandra Shush', ('url') => 'urlof100' ), (1) => Array ( ('uid') => '5465', ('name') => 'Stefanie Mcmohn', ('url') => 'urlof5465' ), (2) => Array ( ('uid') => '40489', ('name') => 'Michael', ('url') => 'urlof40489' ) ); if(array_search('urlof5465', array_column($userdb, 'url')) !== false) { echo 'value is in multidim array'; } else { echo 'value is not in multidim array'; } This idea is in the comments section for array_search() on the PHP manual;
This will work too. function in_array_r($item , $array){ return preg_match('/"'.preg_quote($item, '/').'"/i' , json_encode($array)); } Usage: if(in_array_r($item , $array)){ // found! }
This will do it: foreach($b as $value) { if(in_array("Irix", $value, true)) { echo "Got Irix"; } } in_array only operates on a one dimensional array, so you need to loop over each sub array and run in_array on each. As others have noted, this will only for for a 2-dimensional array. If you have more nested arrays, a recursive version would be better. See the other answers for examples of that.
$userdb = Array ( (0) => Array ( ('uid') => '100', ('name') => 'Sandra Shush', ('url') => 'urlof100' ), (1) => Array ( ('uid') => '5465', ('name') => 'Stefanie Mcmohn', ('url') => 'urlof5465' ), (2) => Array ( ('uid') => '40489', ('name') => 'Michael', ('url') => 'urlof40489' ) ); $url_in_array = in_array('urlof5465', array_column($userdb, 'url')); if($url_in_array) { echo 'value is in multidim array'; } else { echo 'value is not in multidim array'; }
if your array like this $array = array( array("name" => "Robert", "Age" => "22", "Place" => "TN"), array("name" => "Henry", "Age" => "21", "Place" => "TVL") ); Use this function in_multiarray($elem, $array,$field) { $top = sizeof($array) - 1; $bottom = 0; while($bottom <= $top) { if($array[$bottom][$field] == $elem) return true; else if(is_array($array[$bottom][$field])) if(in_multiarray($elem, ($array[$bottom][$field]))) return true; $bottom++; } return false; } example : echo in_multiarray("22", $array,"Age");
For Multidimensional Children: in_array('needle', array_column($arr, 'key')) For One Dimensional Children: in_array('needle', call_user_func_array('array_merge', $arr))
Great function, but it didnt work for me until i added the if($found) { break; } to the elseif function in_array_r($needle, $haystack) { $found = false; foreach ($haystack as $item) { if ($item === $needle) { $found = true; break; } elseif (is_array($item)) { $found = in_array_r($needle, $item); if($found) { break; } } } return $found; }
Since PHP 5.6 there is a better and cleaner solution for the original answer : With a multidimensional array like this : $a = array(array("Mac", "NT"), array("Irix", "Linux")) We can use the splat operator : return in_array("Irix", array_merge(...$a), true) If you have string keys like this : $a = array("a" => array("Mac", "NT"), "b" => array("Irix", "Linux")) You will have to use array_values in order to avoid the error Cannot unpack array with string keys : return in_array("Irix", array_merge(...array_values($a)), true)
You could always serialize your multi-dimensional array and do a strpos: $arr = array(array("Mac", "NT"), array("Irix", "Linux")); $in_arr = (bool)strpos(serialize($arr),'s:4:"Irix";'); if($in_arr){ echo "Got Irix!"; } Various docs for things I used: strpos() serialize() Type Juggling or (bool)
I believe you can just use array_key_exists nowadays: <?php $a=array("Mac"=>"NT","Irix"=>"Linux"); if (array_key_exists("Mac",$a)) { echo "Key exists!"; } else { echo "Key does not exist!"; } ?>
The accepted solution (at the time of writing) by jwueller function in_array_r($needle, $haystack, $strict = false) { foreach ($haystack as $item) { if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) { return true; } } return false; } Is perfectly correct but may have unintended behaviuor when doing weak comparison (the parameter $strict = false). Due to PHP's type juggling when comparing values of different type both "example" == 0 and 0 == "example" Evaluates true because "example" is casted to int and turned into 0. (See Why does PHP consider 0 to be equal to a string?) If this is not the desired behaviuor it can be convenient to cast numeric values to string before doing a non-strict comparison: function in_array_r($needle, $haystack, $strict = false) { foreach ($haystack as $item) { if( ! $strict && is_string( $needle ) && ( is_float( $item ) || is_int( $item ) ) ) { $item = (string)$item; } if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) { return true; } } return false; }
This is the first function of this type that I found in the php manual for in_array. Functions in the comment sections aren't always the best but if it doesn't do the trick you can look in there too :) <?php function in_multiarray($elem, $array) { // if the $array is an array or is an object if( is_array( $array ) || is_object( $array ) ) { // if $elem is in $array object if( is_object( $array ) ) { $temp_array = get_object_vars( $array ); if( in_array( $elem, $temp_array ) ) return TRUE; } // if $elem is in $array return true if( is_array( $array ) && in_array( $elem, $array ) ) return TRUE; // if $elem isn't in $array, then check foreach element foreach( $array as $array_element ) { // if $array_element is an array or is an object call the in_multiarray function to this element // if in_multiarray returns TRUE, than return is in array, else check next element if( ( is_array( $array_element ) || is_object( $array_element ) ) && $this->in_multiarray( $elem, $array_element ) ) { return TRUE; exit; } } } // if isn't in array return FALSE return FALSE; } ?>
Here is my proposition based on json_encode() solution with : case insensitive option returning the count instead of true anywhere in arrays (keys and values) If word not found, it still returns 0 equal to false. function in_array_count($needle, $haystack, $caseSensitive = true) { if(!$caseSensitive) { return substr_count(strtoupper(json_encode($haystack)), strtoupper($needle)); } return substr_count(json_encode($haystack), $needle); } Hope it helps.
I was looking for a function that would let me search for both strings and arrays (as needle) in the array (haystack), so I added to the answer by #jwueller. Here's my code: /** * Recursive in_array function * Searches recursively for needle in an array (haystack). * Works with both strings and arrays as needle. * Both needle's and haystack's keys are ignored, only values are compared. * Note: if needle is an array, all values in needle have to be found for it to * return true. If one value is not found, false is returned. * #param mixed $needle The array or string to be found * #param array $haystack The array to be searched in * #param boolean $strict Use strict value & type validation (===) or just value * #return boolean True if in array, false if not. */ function in_array_r($needle, $haystack, $strict = false) { // array wrapper if (is_array($needle)) { foreach ($needle as $value) { if (in_array_r($value, $haystack, $strict) == false) { // an array value was not found, stop search, return false return false; } } // if the code reaches this point, all values in array have been found return true; } // string handling foreach ($haystack as $item) { if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) { return true; } } return false; }
I used this method works for any number of nested and not require hacking <?php $blogCategories = [ 'programing' => [ 'golang', 'php', 'ruby', 'functional' => [ 'Erlang', 'Haskell' ] ], 'bd' => [ 'mysql', 'sqlite' ] ]; $it = new RecursiveArrayIterator($blogCategories); foreach (new RecursiveIteratorIterator($it) as $t) { $found = $t == 'Haskell'; if ($found) { break; } }
Please try: in_array("irix",array_keys($b)) in_array("Linux",array_keys($b["irix"]) Im not sure about the need, but this might work for your requirement
It works too creating first a new unidimensional Array from the original one. $arr = array("key1"=>"value1","key2"=>"value2","key3"=>"value3"); foreach ($arr as $row) $vector[] = $row['key1']; in_array($needle,$vector);
Shorter version, for multidimensional arrays created based on database result sets. function in_array_r($array, $field, $find){ foreach($array as $item){ if($item[$field] == $find) return true; } return false; } $is_found = in_array_r($os_list, 'os_version', 'XP'); Will return if the $os_list array contains 'XP' in the os_version field.
what about array_search? seems it quite faster than foreach according to https://gist.github.com/Ocramius/1290076 .. if( array_search("Irix", $a) === true) { echo "Got Irix"; }
I found really small simple solution: If your array is : Array ( [details] => Array ( [name] => Dhruv [salary] => 5000 ) [score] => Array ( [ssc] => 70 [diploma] => 90 [degree] => 70 ) ) then the code will be like: if(in_array("5000",$array['details'])){ echo "yes found."; } else { echo "no not found"; }
I have found the following solution not very clean code but it works. It is used as an recursive function. function in_array_multi( $needle, $array, $strict = false ) { foreach( $array as $value ) { // Loop thorugh all values // Check if value is aswell an array if( is_array( $value )) { // Recursive use of this function if(in_array_multi( $needle, $value )) { return true; // Break loop and return true } } else { // Check if value is equal to needle if( $strict === true ) { if(strtolower($value) === strtolower($needle)) { return true; // Break loop and return true } }else { if(strtolower($value) == strtolower($needle)) { return true; // Break loop and return true } } } } return false; // Nothing found, false }
Many of these searches are usually for finding things in a list of records, as some people have pointed out is really a 2-dimensional array. This is for a list of records that have a uniform set of keys) such as a list of records grabbed from a database, among other things. Included are both 'in_array' and 'key_exists' styled functions for this structure for completeness. Both functions return a simple true/false boolean answer. Example 2-dimensional array of records... $records array: [0] => Array ( [first_name] => Charlie [last_name] => Brown ) [1] => Array ( [first_name] => Fred [last_name] => Sanford ) Functions: function in_multidimensional_array($array, $column_key, $search) { return in_array($search, array_column($array, $column_key)); } function multidimensional_array_key_exists($array, $column_key) { return in_array($column_key, array_keys(array_shift($array))); } Tests: var_dump(in_multidimensional_array($records, 'first_name', 'Charlie')); // true var_dump(multidimensional_array_key_exists($records, 'first_name')); // true
you can use like this $result = array_intersect($array1, $array2); print_r($result); http://php.net/manual/tr/function.array-intersect.php
check if array is in two multidimensional array
I have two multidimensional arrays: Haystack $haystack = array ( 0 => array ( "child_element_id" => 11 "answer_id" => 15 ), 1 => array ( "child_element_id" => 12 "answer_id" => 17 ), 2 => array ( "child_element_id" => 13 "answer_id" => 21 ) ) Needle $needle = array ( 0 => array ( "child_element_id" => 12 "answer_id" => 17 ), 1 => array ( "child_element_id" => 13 "answer_id" => 21 ) ) I want to check if all the key values from array "Needle" exists in the array "Haystack". What's the best practice for this? Thank you!
almost a solution: #shalvah gave a good starting point. However, in the suggested solution he forgot to loop over the elements of the $needle array like shown below: function array_in_array($neearr,$haystack) { foreach ($neearr as $needle){ foreach ($haystack as $array) { //check arrays for equality if(count($needle) == count($array)) { $needleString = serialize($needle); $arrayString = serialize($array); echo "$needleString||$arrayString<br>"; if(strcmp($needleString, $arrayString) == 0 ) return true; } return false; } } } But even so is this not completely "water tight". In cases where elements of the "needle" arrays appear in a different order (sequence) the serialze()-function will produce differing strings and will lead to false negatives, like shown in the exampe below: $hay=array(array('a'=>'car','b'=>'bicycle'), array('a'=>'bus','b'=>'truck'), array('a'=>'train','b'=>'coach')); $nee1=array(array('a'=>'car','b'=>'bicycle'), array('a'=>'train','b'=>'coach')); $nee2=array(array('b'=>'bicycle','a'=>'car'), // different order of elements! array('a'=>'train','b'=>'coach')); echo array_in_array($nee1,$hay); // true echo array_in_array($nee2,$hay); // false (but should be true!) a slightly better solution This problem can be solved by first sorting (ksort(): sort by key value) all the elements of all the "needle" arrays before serialize-ing them: function array_in_array($neearr,$haystack) { $haystackstrarr = array_map(function($array){ksort($array);return serialize($array);},$haystack); foreach ($neearr as $needle){ ksort($needle); $needleString = serialize($needle); foreach ($haystackstrarr as $arrayString){ if(strcmp($needleString, $arrayString) == 0 ) return true; } return false; } } echo array_in_array($nee1,$hay); // true echo array_in_array($nee2,$hay); // true
Pretty easy using in_array() since needle can be an array: $found = 0; foreach($needle as $array) { if(in_array($array, $haystack, true)) { $found++; } } if($found === count($needle)) { echo 'all needles were found in haystack'; } Or maybe: $found = true; foreach($needle as $array) { if(!in_array($array, $haystack, true)) { $found = false; break; } } if($found) { echo 'all needles were found in haystack'; } You could even use array_search() as you can use an array for needle as well, no need to run two loops. Using serialize(): if(count(array_map('unserialize', array_intersect(array_map('serialize', $needle), array_map('serialize',$haystack)))) == count($needle)) { echo 'all needles were found in haystack'; } serialize() the inner arrays of both arrays and compute the intersection (common inner arrays) unserialize() the result and compare the count() with the count of $needle
You could use this function: function array_in_array(array $needle, array $haystack) { foreach($needle as $nearr) { foreach ($haystack as $array) { //check arrays for equality if(count($needle) == count($array)) { $needleString = serialize($needle); $arrayString = serialize($array); if(strcmp($needleString, $arrayString) == 0 ) return true; } } return false; }
in_array() not finding needle in haystack
I have a simple in_array statement in PHP. It's looking for the this needle: 926296884640412424_1534875699 In this haystack: Array ( [0] => Array ( [id] => 926296884640412424_1534875699 ) [1] => Array ( [id] => 926301883885225094_723729160 ) ) My code is like this: if(!in_array($object->id, $Admin->hiddenItems, true)) { // Always fires } else { // Never fires } And it never finds it. I've tried both with strict set to TRUE and FALSE, but neither works. What am I doing wrong?
You're searching in a multidimensional array. Flatten it before using in_array(): if (!in_array($object->id, array_column($Admin->hiddenItems, 'id'), true)) { ... }
<?php $arrays = array( array( 'id' => '926296884640412424_1534875699' ), array( 'id' => '926301883885225094_723729160' ) ); print exist('926296884640412424_1534875699', $arrays); function exist($id, $arrays) { foreach ($arrays as $array) { if (in_array($id, $array)) { return "exist"; } } return "no exist"; }
You can use this recursive function as well to search certain value in multidimensional arrays: function multi_in_array_r($needle, $haystack) { if(in_array($needle, $haystack)) { return true; } foreach($haystack as $element) { if(is_array($element) && multi_in_array_r($needle, $element)) return true; } return false; } It's up to you to decide what gives best results, because as you can see there are few different way to accomplish the same thing.
Using in_array for multidimensional arrays
Ok, so I have this array :- 0 => array (size=2) 'receiver_telmob' => string '0707105396' (length=10) 0 => string '0707105396' (length=10) 1 => array (size=2) 'receiver_telmob' => string '0704671668' (length=10) 0 => string '0704671668' (length=10) 2 => array (size=2) 'receiver_telmob' => string '0707333311' (length=10) 0 => string '0707333311' (length=10) And I'm trying to search in this array using in_array. But, I never get any true value. Here's what I'm trying to do:- $searchnumber = '0707333311'; if(in_array($searchnumber,$arrayAbove)) { //do something } But the if always results a false output. I guess that I'm not using the in_array correctly here. What should I correct to make it work? Thanks.
$array = array( "0" => array( "receiver_telmob" => "0707105396", "0" => "0707105396" ), "1" => array( "receiver_telmob" => "0704671668", "0" => "0704671668" ), "2" => array( "receiver_telmob" => "0707333311", "0" => "0707333311" ) ); $searchnumber = "0707333311"; foreach($array as $v) { if ($v['receiver_telmob'] == $searchnumber) { $found = true; } } echo (isset($found) ? 'search success' : 'search failed');
in_array() doesn't work with multi-dimensional arrays. You need something like this - function in_multi_array($needle, $haystack, $strict = false) { foreach ($haystack as $item) { if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_multi_array($needle, $item, $strict))) { return true; } } return false; } Then you could do this - $searchnumber = '0707333311'; if(in_multi_array($searchnumber,$arrayAbove)) { //do something }
You can't use in_array for multidimensional arrays! But this function should work for you: <?php function in_array_r($needle, $haystack, $strict = false) { foreach ($haystack as $item) { if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) { return true; } } return false; } ?> Then you can use it like this: echo in_array_r("0707333311", $arrayAbove) ? 'true(found)' : 'false(not found)';
You would have to use in_array for each sub array. So if you have a 1 dimensional array like [1,4,43,2,5,4] you could call in_array but when you have multidimensional you have to iterate over the top dimension and call in_array for($i = 0;$i < arr.count(); $i++){ if(in_array($searchnum, $arr[$i]){ //do something } } NOTE: the example above only works for 2d arrays just to demonstrate what I was talking about
Try this: function in_array_recursive($needle, $haystack) { foreach($haystack as $item) { if ($needle = $item || is_array($item) && in_array_recursive($needle, $item)) return true; } } return false; } $searchnumber = '0707333311'; if(in_array_recursive($searchnumber,$arrayAbove)) { //do something }
Check if specific array key exists in multidimensional array - PHP
I have a multidimensional array e.g. (this can be many levels deep): $array = Array ( [21] => Array ( ) [24] => Array ( [22] => Array ( ) [25] => Array ( [26] => Array ( ) ) ) ) I am trying to loop through it to see if a certain key exists: $keySearch = 22; // key searching for function findKey($array, $keySearch) { foreach ($array as $item){ if (isset($item[$keySearch]) && false === findKey($item[$keySearch], $item)){ echo 'yes, it exists'; } } } findKey($array, $keySearch); But it finds nothing. Is there an error in the loop?
array_key_exists() is helpful. Then something like this: function multiKeyExists(array $arr, $key) { // is in base array? if (array_key_exists($key, $arr)) { return true; } // check arrays contained in this array foreach ($arr as $element) { if (is_array($element)) { if (multiKeyExists($element, $key)) { return true; } } } return false; } Working example: http://codepad.org/GU0qG5su
I played with your code to get it working : function findKey($array, $keySearch) { foreach ($array as $key => $item) { if ($key == $keySearch) { echo 'yes, it exists'; return true; } elseif (is_array($item) && findKey($item, $keySearch)) { return true; } } return false; }
Here is a one line solution: echo strpos(json_encode($array), $key) > 0 ? "found" : "not found"; This converts the array to a string containing the JSON equivalent, then it uses that string as the haystack argument of the strpos() function and it uses $key as the needle argument ($key is the value to find in the JSON string). It can be helpful to do this to see the converted string: echo json_encode($array); Be sure to enclose the needle argument in single quotes then double quotes because the name portion of the name/value pair in the JSON string will appear with double quotes around it. For instance, if looking for 22 in the array below then $key = '"22"' will give the correct result of not found in this array: $array = Array ( 21 => Array ( ), 24 => Array ( 522 => Array ( ), 25 => Array ( 26 => Array ( ) ) ) ); However, if the single quotes are left off, as in $key = "22" then an incorrect result of found will result for the array above. EDIT: A further improvement would be to search for $key = '"22":'; just incase a value of "22" exists in the array. ie. 27 => "22" In addition, this approach is not bullet proof. An incorrect found could result if any of the array's values contain the string '"22":'
function findKey($array, $keySearch) { // check if it's even an array if (!is_array($array)) return false; // key exists if (array_key_exists($keySearch, $array)) return true; // key isn't in this array, go deeper foreach($array as $key => $val) { // return true if it's found if (findKey($val, $keySearch)) return true; } return false; } // test $array = Array ( 21 => Array ( 24 => 'ok' ), 24 => Array ( 22 => Array ( 29 => 'ok' ), 25 => Array ( 26 => Array ( 32 => 'ok' ) ) ) ); $findKeys = Array(21, 22, 23, 24, 25, 26, 27, 28, 29, 30); foreach ($findKeys as $key) { echo (findKey($array, $key)) ? 'found ' : 'not found '; echo $key.'<br>'; }
returns false if doesn't exists, returns the first instance if does; function searchArray( array $array, $search ) { while( $array ) { if( isset( $array[ $search ] ) ) return $array[ $search ]; $segment = array_shift( $array ); if( is_array( $segment ) ) { if( $return = searchArray( $segment, $search ) ) return $return; } } } return false; }
For sure some errors, is this roughly what you are after? (Untested code): $keySearch=22; // key seraching for function findKey($array, $keySearch) { // check whether input is an array if(is_array($array) { foreach ($array as $item) { if (isset($item[$keySearch]) || findKey($item, $keysearch) === true) { echo 'yes, it exists'; return true; } } } }
Here is one solution that finds and return the value of the key in any dimension array.. function findValByKey($arr , $keySearch){ $out = null; if (is_array($arr)){ if (array_key_exists($keySearch, $arr)){ $out = $arr[$keySearch]; }else{ foreach ($arr as $key => $value){ if ($out = self::findValByKey($value, $keySearch)){ break; } } } } return $out; }
I did modified to return value of searched key: function findKeyInArray($array, $keySearch, &$value) { foreach ($array as $key => $item) { if ($key === $keySearch) { $value = $item; break; } elseif (is_array($item)) { findKeyInArray($item, $keySearch,$value); } } } $timeZone = null; findKeyInArray($request, 'timezone', $timeZone);