Is there a function like in_array() than can, check conntent inside array of arrays?
I tried:
$day_events = Array();
array_push($day_events,array('aa','bb','cc'));
array_push($day_events,array('aa','bc','cd'));
array_push($day_events,array('ac','bd','ce'));
echo '<br />';
echo in_array('aa',$day_events); // empty
echo '<br />';
foreach ($day_events as &$value) {
echo in_array('aa',$value); // 11
}
first in_array() which is the kind of function I am looking for (avoiding the loop) gave empty.
Use this function, as in_array doesn't natively support multi-dimensional arrays:
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;
}
In this case you would you use it like this:
echo in_array_r('aa', $day_events) ? 'Found' : 'Not found';
It was taken from this answer: https://stackoverflow.com/a/4128377/2612112.
By the way it is not avoiding first one it is avoiding the last one which has 'ac'. So you get true from first two. Your code works but I am not sure if that is what you want.
Related
i have a problem with a php if condition
i have follow variables and arrays:
<?php
$appartamenti = array("97", "98", "99", "100");
$appartamentinoloft = array("97", "98", "99");
$case = array("103", "104", "107", "108");
$casevacanze = array("109", "110", "111", "112");
$stanze = array("115", "116");
$uffici = array("113", "114");
$locali = array("117", "118");
$garage = array("119", "120");
$terreni = array("121", "122");
$cantine = array("123", "124");
$tuttenoterreni = array($appartamenti, $case, $casevacanze, $uffici, $garage, $cantine);
?>
and i have this if condition:
<?php if ( osc_item_category_id() == $terreni) { ?>
<?php echo $custom_field_value['dimensioni-terreni'] ;?> mq
<?php } else if ( osc_item_category_id() == $tuttenoterreni) { ?>
<?php echo $custom_field_value['dimensioni'] ;?> mq
<?php } else { ?>
<?php } ?>
osc_item_category_id() is a number value
but not work.
i don't understand where is problem...
$terreni is single dimensional array and $tuttenoterreni is multi dimensional array.
For a single dimensional array, use in_array() function and for multi dimesnional array, create a custom function to find values in this multi dimensional array.
I've provided you the following code, which will help you to find values in multi dimensional array. Follow in_array() and multidimensional array
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;
}
Code:
<?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;
}
if (in_array(osc_item_category_id(),$terreni)) {
echo $custom_field_value['dimensioni-terreni'] ;
} elseif(in_array_r(osc_item_category_id(), $tuttenoterreni)) {
echo $custom_field_value['dimensioni'] ;
} else {
echo "Oops.!! No results found.";
}?>
Useful Links:
in_array() - PHP Manual
in_array() and multidimensional array
You can't check "directly" this. You are trying to compare two type of variables.
An PHP array is a pointer to "multiple variables".
If I read your code correctly, probably your function osc_item_category_id returns an integer. In that case, the first if will change to:
<?php if (in_array(osc_item_category_id(), $terreni)) { ?>
You can check documentation about in_array function here: http://be2.php.net/manual/en/function.in-array.php.
The elseif, have a similar problem. You've created a multidimensional array (an array of arrays). You need to use on this place the array_merge function (check documentation here: http://be2.php.net/manual/en/function.array-merge.php), to create a unique array with all values of the another ones. Then, you can check as on the first example:
$tuttenoterreni = array_merge($appartamenti, $case, $casevacanze, $uffici, $garage, $cantine);
<?php } else if (in_array(osc_item_category_id(), $tuttenoterreni)) { ?>
if osc_item_category_id() function return no. 121,122 user this function to compare.
<?php
$in_id = osc_item_category_id();
if(in_array($in_id,$terreni)){
echo $custom_field_value['dimensioni-terreni'];
}
?>
The in_array() function searches an array for a specific value.
Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.
Syntax:
in_array(search,array,type)
Example :
$people = array("Peter", "Joe", "Glenn", "Cleveland");
if (in_array("Glenn", $people)){
echo "Match found";
}
Use the function
bool in_array ( value , array )
this function returns true is the value is present in the array
So modify the content of if and else if condition in your code, e.g:
if(in_array(osc_item_category_id() , $terreni ))
Also what I notice in your code is that in the elseif part you are trying to compare a numerical value returned by osc_item_category_id() with the value in the 'array of array', whereas in 'if' condition you are comparing the value returned by osc_item_category_id() with value in 'array'.
If it is the fact then in elseif part you need to run a foreach loop, comparing the value returned by 'osc_item_category_id()' with each array using the above 'in_array()' method.
Hope this help out!!!
I want check my array value with in_array my arrays this is:
I use this code but it's not work
if(in_array(167, $array) AND in_array(556, $array) ) {
echo 'ok';
return;
}
now how can check my values?
in_array() does not work for multi-dimensional arrays , you either have to loop it and do the in_array() check or merge the array into a single one and then do single in_array() check.
Way 1:
foreach($array as $k=>$arr)
{
if(in_array(167,$arr))
{
echo "Found";
}
}
Way 2: (Merge)
$merged_arr = call_user_func_array('array_merge', $array);
if(in_array(167,$merged_arr))
{
echo "Found";
}
EDIT :
<?php
$array = array(array(167),array(167),array(556));
$merged_arr = call_user_func_array('array_merge', $array);
$needle_array = array(167,556,223);
foreach($needle_array as $v)
{
if(in_array($v,$merged_arr))
{
echo "Found";
}
}
You can even use array_intersect() on these two arrays to get the matched content , if that is what you are looking for.
You could create a mult-dimensional in_array function:
function inArrayMulti($needle, $haystack, $strict=false) {
foreach( $haystack as $item ) {
if( is_array($item) ) return inArrayMulti($needle, $item);
else {
if( $strict && $needle === $item) ) return true;
else if( $needle == $item ) return true;
}
}
return false;
}
May be useful this
return 0 < count(
array_filter(
$my_array,
function ($a) {
return array_key_exists('id', $a) && $a['id'] == 152;
}
)
);
Or
$lookup_array=array();
foreach($my_array as $arr){
$lookup_array[$arr['id']]=1;
}
Now you can check for an existing id very fast, for example:
echo (isset($lookup_array[152]))?'yes':'no';
Loop through the array
<?php
foreach($array as $ar){
if(in_array(167,$ar) && in_array(556,$ar)){
echo "ok";
}
}
?>
Why all answers use in_array and other difficult construction? We need found only two numbers, easy way for this:
$array = array(array(165), array(167),array(167),array(556));
foreach($array as $key){
foreach($key as $next){
echo 167 == $next || 556 == $next ? '<p>Found<p></br>' : '';
}
}
I'm trying to find a part of a string in a multidimentional array.
foreach ($invitees as $invitee) {
if (in_array($invitee, $result)){
echo 'YES';
} else {
echo 'NO';
}
}
the $invitees array has 2 elements:
and $result is what I get from my Drupal database using db_select()
What I'm trying to do is, if the first part from one of the emails in $invitees is in $result it should echo "YES". (the part before the "#" charather)
For example:
"test.email" is in $result, so => YES
"user.one" is not in $result, so => NO
How do i do this? How can I search for a part of a string in a multidimentional array?
Sidenote: I noticed that the array I get from Drupal ($result) has 2 "Objects" which contain a "String", and not arrays like I would expect.
For example:
$test = array('red', 'green', array('apple', 'banana'));
Difference between $result and $test:
Does this have any effect on how I should search for my string?
Because $result is an array of objects, you'll need to use a method to access the value and compare it. So, for instance you could do:
//1: create new array $results from array of objects in $result
foreach ($result as $r) {
$results[] = get_object_vars($r);
}
//2: expanded, recursive in_array function for use with multidimensional arrays
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;
}
//3: check each element of the $invitees array
foreach ($invitees as $invitee) {
echo in_array_r($invitee, $results) ? "Yes" : "No";
}
Also, for some illumination, check out this answer.
You can search through the array using preg_grep, and use a wildcard for anything before and after it. If it returns a value (or values), use key to get the index of the first one. Then do a check if its greater than or equal to 0, which means it found a match :)
<?php
$array = array('test1#gdfgfdg.com', 'test2#dgdgfdg.com', 'test3#dfgfdgdfg');
$invitee = 'test2';
$result = key(preg_grep('/^.*'.$invitee.'.*/', $array));
if ($result >= 0) {
echo 'YES';
} else {
echo 'NO';
}
?>
Accepted larsAnders's answer since he pointed me in to direction of recursive functions.
This is what I ended up using (bases on his answer):
function Array_search($array, $string) {
foreach ($array as $key => $value) {
if (is_array($value)) {
Array_search($array[$key], $string);
} else {
if ($value->data == $string) {
return TRUE;
}
}
}
return FALSE;
}
I have an array that has "formname" in it as a $key. When I execute the following function:
function in_array_r($needle, $arr, $strict = true) {
$form_id = $lead['form_id'];
$user_id = $lead['id'];
$attachments = array();
$arr=get_defined_vars();
$needle="formna1me";
foreach ($arr as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
echo "found"; exit;
}
}
echo "notfound"; exit;
}
It returns "found" as it should. But if I change the $needle to $needle = "bbrubrcuyrfbur" it also returns found. It is simply always returning found? Not sure what is wrong.
You are calling the function recursively. Even when you call the function with needle as bbrubrcuyrfbur, in the if condition the function is called recursively with needle as formna1me.
Inside the first recursion, $arr=get_defined_vars(); will read the value of $needle as formna1me. Then $needle will be reassigned formna1me and the if condition will match formna1me from $needle with the one in $args.
Lines 2 to 6 should probably not be in that function.
is_array supposed to work like below you are checking the item in is_array instead of array
$yes = array('this', 'is', 'an array');
echo is_array($yes) ? 'Array' : 'not an Array';
what is_array is doing is that
is_array — Finds whether a variable is an array
as your comment
tofind that the value is in array try in_array — Checks if a value exists in an array
$arr = array("Mac", "NT", "msc", "Linux");
if (in_array("Linux", $arr)) {
echo 'yes it is';
}
I am trying to write a piece of code that searches one column of 2-D array values and returns the key when it finds it. Right now I have two functions, one to find a value and return a boolean true or false and another (not working) to return the key. I would like to merge the two in the sense of preserving the recursive nature of the finding function but returning a key. I cannot think how to do both in one function, but working key finder would be much appreciated.
Thanks
function in_array_r($needle, $haystack, $strict = true) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
function loopAndFind($array, $index, $search){
$returnArray = array();
foreach($array as $k=>$v){
if($v[$index] == $search){
$returnArray[] = $k;
}
}
return $returnArray;
}`
Sorry, I meant to add an example. For instance:
Array [0]{
[0]=hello
[1]=6
}
[1]
{
[0]=world
[1]=4
}
and I want to search the array by the [x][0] index to check each string of words for the search term. If found, it should give back the index/key in the main array like "world" returns 1
This works:
$array = array(array('hello', 6), array('world', 4));
$searchTerm = 'world';
foreach ($array as $childKey => $childArray) {
if ($childArray['0'] == $searchTerm) {
echo $childKey; //Your Result
}
}
You already have all you need in your first function. PHP does the rest:
$findings = array_map('in_array_r', $haystack);
$findings = array_filter($findings); # remove all not found
var_dump(array_keys($findings)); # the keys you look for