php if condition with search in array values - php

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!!!

Related

Search for part of string in multidimentional array returned by Drupal

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

in_array() for array of array

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.

PHP in_array function not working with multidimensional array in loop

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

PHP Search Multidimensional Array - Not Associative

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

using array_map to test values?

Is it possible to use array_map() to test values of an array? I want to make sure that all elements of an array are numeric.
I've tried both
$arrays = array(
array(0,1,2,3 )
, array ( 0,1, "a", 5 )
);
foreach ( $arrays as $arr ) {
if ( array_map("is_numeric", $arr) === FALSE ) {
echo "FALSE\n";
} else {
echo "TRUE\n";
}
}
and
$arrays = array(
array(0,1,2,3 )
, array ( 0,1, "a", 5 )
);
foreach ( $arrays as $arr ) {
if ( ( array_map("is_numeric", $arr) ) === FALSE ) {
echo "FALSE\n";
} else {
echo "TRUE\n";
}
}
And for both I get
TRUE
TRUE
Can this be done? If so, what am I doing wrong?
Note: I am aware that I can get my desired functionality from a foreach loop.
array_map returns an array. So it will always be considered 'true'. Now, if you array_search for FALSE, you might be able to get the desire effects.
From the PHP.net Page
array_map() returns an array containing all the elements of
arr1 after applying the callback function to each one.
This means that currently you have an array that contains true or false for each element. You would need to use array_search(false,$array) to find out if there are any false values.
I'm usually a big advocate of array_map(), array_filter(), etc., but in this case foreach() is going to be the best choice. The reason is that with array_map() and others it will go through the entire array no matter what. But for your purposes you only need to go through the array until you run into a value for which is_numeric() returns false, and as far as I know there's no way in PHP to break out of those methods.
In other words, if you have 1,000 items in your array and the 5th one isn't numeric, using array_map() will still check the remaining 995 values even though you already know the array doesn't pass your test. But if you use a foreach() instead and have it break on is_numeric() == false, then you'll only need to check those first five elements.
You could use filter, but it ends up with a horrible bit of code
$isAllNumeric = count(array_filter($arr, "is_numeric")) === count($arr)
Using a custom function makes it a bit better, but still not perfect
$isAllNumeric = count(array_filter($arr, function($x){return !is_numeric($x);})) === 0
But if you were using custom functions array_reduce would work, but it still has some failings.
$isAllNumeric = array_reduce($arr,
function($x, $y){ return $x && is_numeric($y); },
true);
The failings are that it won't break when it has found what it wants, so the functional suggestions above are not very efficient. You would need to write a function like this:
function array_find(array $array, $callback){
foreach ($array as $x){ //using iteration as PHP fails at recursion
if ( call_user_func($callback, array($x)) ){
return $x;
}
}
return false;
}
And use it like so
$isAllNumeric = array_find($arr, function($x){return !is_numeric($x);})) !== false;
i have two tiny but extremely useful functions in my "standard library"
function any($ary, $func) {
foreach($ary as $val)
if(call_user_func($func, $val)) return true;
return false;
}
function all($ary, $func) {
foreach($ary as $val)
if(!call_user_func($func, $val)) return false;
return true;
}
in your example
foreach ( $arrays as $arr )
echo all($arr, 'is_numeric') ? "ok" : "not ok";
A more elegant approach IMHO:
foreach ($arrays as $array)
{
if (array_product(array_map('is_numeric', $array)) == true)
{
echo "TRUE\n";
}
else
{
echo "FALSE\n";
}
}
This will return true if all the values are numeric and false if any of the values is not numeric.

Categories