PHP array_key_exists and is not empty - php

Following on from a previous question, I am now using the following function to check if a key exists in a multi-dimensional array...
function array_key_exists_r($needle, $haystack) {
$result = array_key_exists($needle, $haystack);
if ($result)
return $result;
foreach ($haystack as $v) {
if (is_array($v) || is_object($v))
$result = array_key_exists_r($needle, $v);
if ($result)
return $result;
}
return $result;
}
I am checking like this...
if (array_key_exists_r("image",$myarray)) {
echo 'Array Key Image Exists';
}
But now I am trying to modify it or the result to check that key is not empty, can I do this inside the function or should I do something with the output of the function?
Or should I be using isset instead?

Whether you do this inside the function or not it's fully up to you. Personally if I did it inside the function I would change its name to something clearer since it doesn't only check if a key exists. Anyhow I found a solution within the same function:
function array_key_exists_r($needle, $haystack){
$result = array_key_exists($needle, $haystack);
if ($result && $haystack[$needle]){
return $result;
}
foreach ($haystack as $v)
{
if (is_array($v) || is_object($v)){
$result = array_key_exists_r($needle, $v);
if ($result) {
return $result;
}
}
}
return false;
}
So basically I added a validation on your ifs and that did it also change the default return value to false just in case. I think it can still be enhanced but this does the job.

Try this approach instead. Easier!
function array_key_exists_r($needle, $haystack) {
$found = [];
array_walk_recursive($haystack, function ($key, $value) use (&$found) {
# Collect your data here in $found
});
return $found;
}

Related

Function with loop calling same function in PHP

I'm having a trouble. I was trying to make it work for a long time, so I decided to ask for help here.
I have an with some arrays inside it:
$myarray = [
['string1','string2'],
['string3','string4'],
['string5',['string6','string7','string99']],
['string8','string9']
];
I am making a function that search for a s
function searchArray($array,$chave,$id) {
foreach ($array as $key) {
if (is_array($key)) {
if (($key[0] == $chave) && ($key[1] == $id)) {
break;
}
else {
searchArray($key,$chave,$id);
}
}
}
return $key;
}
$result = searchArray($myarray,'string6','string7');
print_r($result);
It was supposed to print ['string6','string7','string99']]
But it it printing the last "key" of the array: ['string8','string9']
The break is not working. After the break, it continue checking the next arrays.
with these modification it returns the expected values:
<?php
$myarray = [
['string1','string2'],
['string3','string4'],
['string5',['string6','string7','string99']],
['string8','string9']
];
function searchArray($array,$chave,$id) {
foreach ($array as $key) {
if (is_array($key)) {
if (($key[0] == $chave) && ($key[1] == $id)) {
return $key;
} else {
$res = searchArray($key,$chave,$id);
if($res !== false) {
return $res;
}
}
}
}
return false;
}
$result = searchArray($myarray,'string6','string7');
print_r($result);
the failure was to break on success. That makes no sense.
You need to return the value on success. If no success return false. Imagine it may happen that the searched values will not been found so it should return false.

Why "return" on PHP function is not stopping the process?

I do not understand why "return" is not stopping the process in this function that I created to search a value on a multi_level array in PHP.
This is the code:
static function in_array_multi($needle, $haystack) {
foreach ($haystack as $item) {
if(is_array($item)){
in_array_multi($needle, $item);
}
else{
if ($item === $needle) {
return "ok";
}
}
}
return "nok";
}
I am using this array as exemple:
$arr = array(0 => array(id=>1,name=>"cat 1"),
1 => array(id=>2,name=>"cat 2"),
2 => array(id=>3,name=>array(id=>7,name=>"cat 7"))
);
And I am calling the function like this:
echo in_array_multi("cat 1",$arr);
It is returning "nok".
I am using xdebug to follow the process. It should stop the process on the second round.
Someone has any idea about what is happening?
Thanks
My comment was a bit careless. You would only want to return directly from the recursion if the recursion actually finds the value. You could do
function in_array_multi($needle, $haystack) {
foreach ($haystack as $item) {
if(is_array($item)){
if ('ok' === in_array_multi($needle, $item)) {
return 'ok';
}
}
elseif ($item === $needle) {
return "ok";
}
}
return "nok";
}
Because you make the return of function will stop the loop, you should collect it and return in the final.
Maybe you want this..
function array_multiple_search($array, $key, $value=null) {
$return = array();
if (is_array($array)) {
if (isset($array[$key])) {
if (is_null($value)) {
$return[] = $array;
} elseif ($array[$key] == $value) {
$return[] = $array;
}
}
foreach ($array as $subarray) {
$return = array_merge($return, array_multiple_search($subarray, $key, $value));
}
}
return $return;
}
param 1 is the target array
param 2 is the key you want to search of target array
param 3 is the value you want to search with the key of target array(can null)
This function will collect and return an array of qualified.

Search a number in string formatted array in PHP?

My array looks like this:
array( '0|500|0.50', '501|1000|0.75' );
I am trying to run a search to get the KEY which has the searched value.
I made this function to search:
function cu_array_search($str,$array){
foreach($array as $key => $value) {
if(strstr($str,$value)) {
return true;
} else {
return false;
}
}
}
and using it like this when checking:
if (cu_array_search(500,$array) {
but it never return true, despite that 500 exists in first key in array .
How to resolve this?
Thanks
strpos will make you function return true even that's 0.5001 but not 500.
You should explode the value by |, then check whether the number in the array.
function cu_array_search($num, $array){
return count(array_filter($array, function ($var) use ($num) {
return in_array($num, explode('|', $var));
})) > 0;
}
The haystack is the first argument, not the second:
if(strstr($value,$str)) {
Additionally, strpos is faster at this, so you should use:
function cu_array_search($str,$array){
foreach($array as $key => $value) {
if(strpos($value,$str) !== false) {
return $key;
} else {
return false;
}
}
}
First, strstr parameters are wrong
Second, return false should be at the end of the loop.
Third, If you need KEY then You need to use return $key instead of return true
function cu_array_search($str,$array){
foreach($array as $key => $value) {
if(strstr($value, $str)) {
return $key;
}
}
return false;
}
This works fine
<?php
function cu_array_search($str, $array) {
foreach($array as $key => $value) {
$temp_array=explode('|', $value);
if (in_array($str, $temp_array))
return true;
}
return false;
}
$array = array( '0|500|0.50', '501|1000|0.75' );
if (cu_array_search(500, $array))
echo "success";
else
echo "failed" ;
?>

PHP looping multidimensional array

Not entirely sure how to adequately title this problem, but it entails a need to loop through any array nested within array, of which may also be an element of any other array - and so forth. Initially, I thought it was required for one to tag which arrays haven't yet been looped and which have, to loop through the "base" array completely (albeit it was learned this isn't needed and that PHP somehow does this arbitrarily). The problem seems a little peculiar - the function will find the value nested in the array anywhere if the conditional claus for testing if the value isn't found is omitted, and vice versa. Anyway, the function is as followed:
function loop($arr, $find) {
for($i=0;$i<count($arr);$i++) {
if($arr[$i] == $find) {
print "Found $find";
return true;
} else {
if(is_array($arr[$i])) {
$this->loop($arr[$i], $find);
} else {
print "Couldn't find $find";
return false;
}
}
}
}
Perhaps you should change your code to something like:
var $found = false;
function loop($arr, $find) {
foreach($arr as $k=>$v){
if($find==$v){
$this->found = true;
}elseif(is_array($v)){
$this->loop($v, $find);
}
}
return $this->found;
}
This has been working for me for a while.
function array_search_key( $needle_key, $array ) {
foreach($array AS $key=>$value){
if($key == $needle_key) return $value;
if(is_array($value)){
if( ($result = array_search_key($needle_key,$value)) !== false)
return $result;
}
}
return false;
}
OK, what about a slight modification:
function loop($arr, $find) {
for($i=0;$i<count($arr);$i++) {
if(is_array($arr[$i])) {
$this->loop($arr[$i], $find);
} else {
if($arr[$i] == $find) {
print "Found $find";
return true;
}
}
}
return false;
}
Hmm?
Try this: PHP foreach loop through multidimensional array

Checking if Any Item in Array is Found in a String

I know this question has been asked before but I haven't been able to get the provided solutions to work.
I'm trying to check if the words in an array match any of the words (or part of the words) in a provided string.
I currently have the following code, but it only works for the very first word in the array. The rest of them always return false.
"input" would be the "haystack" and "value" would be the "needle"
function check($array) {
global $input;
foreach ($array as $value) {
if (strpos($input, $value) !== false) {
// value is found
return true;
} else {
return false;
}
}
}
Example:
$input = "There are three";
if (check(array("one","two","three")) !== false) {
echo 'This is true!';
}
In the above, a string of "There is one" returns as true, but strings of "There are two" or "There are three" both return false.
If a solution that doesn't involve having to use regular expressions could be used, that would be great. Thanks!
The problem here is that check always returns after the first item in $array. If a match is found, it returns false, if not, it returns true. After that return statement, the function is done with and the rest of the items will not be checked.
function check($array) {
global $input;
foreach($array as $value) {
if(strpos($input, $value) !== false) {
return true;
}
}
return false;
}
The function above only returns true when a match is found, or false when it has gone through all the values in $array.
strpos(); is totally wrong here, you should simply try
if ($input == $value) {
// ...
}
and via
if ($input === $value) { // there are THREE of them: =
// ...
}
you can even check if the TYPE of the variable is the same (string, integer, ...)
a more professional solution would be
in_array();
which checks for the existance of the key or the value.
The problem here is that you're breaking out of the function w the return statement..so u always cut out after the first comparison.
you should use in_array() to compare the array values.
function check($array) {
global $input;
foreach ($array as $value) {
if (in_array($value,$input))
{
echo "Match found";
return true;
}
else
{
echo "Match not found";
return false;
}
}
}
You're returning on each iteration of $array, so it will only run once. You could use stristr or strstr to check if $value exists in $input.
Something like this:
function check($array) {
global $input;
foreach ($array as $value) {
if (stristr($input, $value)) {
return true;
}
}
return false;
}
This will then loop through each element of the array and return true if a match is found, if not, after finishing looping it will return false.
If you need to check if each individual item exists in $input you'd have to do something a little bit different, something like:
function check($array) {
global $input;
$returnArr = array();
foreach ($array as $value) {
$returnArr[$value] = (stristr($input, $value)) ? true : false;
}
return $returnArr;
}
echo '<pre>'; var_dump(check($array, $input)); echo '</pre>';
// outputs
array(3) {
["one"]=>
bool(false)
["two"]=>
bool(false)
["three"]=>
bool(true)
}
The reason your code doesnt work, is because you are looping through the array, but you are not saving the results you are getting, so only the last result "counts".
In the following code I passed the results to a variable called $output:
function check($array) {
global $input;
$output = false;
foreach ($array as $value) {
if (strpos($input, $value) != false) {
// value is found
$output = true;
}
}
return $output;
}
and you can use it like so:
$input = "There are two";
$arr = array("one","two","three");
if(check($arr)) echo 'this is true!';

Categories