in_array fails when using implode in if statement - php

This attamept is to create a search condition where eventually the output will be processed to show results based on increasing order of matches
"PHP implode function in if and foreach condition [closed]" is a different question !
Why is the following code failing ?
$terms = array("HELLO", "HI", "HOWDY");
$row = array("HELLO", "HI", "Hey");
$chkcond = "in_array('".implode("',$"."row".")"." && in_array"."('",$terms)."',$"."row)";
echo "$chkcond<br/><br/>";
if ($chkcond) {
echo "All Found in Array !<br>";}else{echo "Not Found !<br/>";
}
The echo result is
in_array('HELLO',$row) && in_array('HI',$row) && in_array('HOWDY',$row)
And the if condition outputs "All Found in Array !"
When the if condition says that all three terms have to be in the row array to be "All Found in Array", then why is it returning True when "Howdy" doesn't exist in the row array ?

juste use array_diff http://php.net/array_diff
<?php
$terms=array("HELLO","HI","HOWDY");
$row=array("HELLO","HI","Hey");
$diff = array_diff($terms, $row);
if (0 === count($diff)){echo "All terms Found in Array row !<br>";}else{echo "Not all terms Found in Array row !<br>";}
$terms=array("HELLO","HI","HOWDY");
$row=array("HELLO","HI","Hey","HOWDY");
$diff = array_diff($terms, $row);
if (0 === count($diff)){echo "All terms Found in Array row !<br>";}else{echo "Not all terms Found in Array row !<br>";}

You could use array_diff
Something like:
<?php
$terms=array("HELLO","HI","HOWDY");
$row=array("HELLO","HI","Hey");
$chkcond=array_diff($terms, $row);
var_dump($chkcond);
if(empty($chkcond)) {
echo "All Found in Array !<br>";
} else {
echo "Not Found !<br>";
}
?>

Not sure what you are attempting but you can use array_diff.
$terms = array("HELLO","HI","HOWDY");
$row = array("HELLO","HI","Hey");
$differences = array_diff($terms, $row);
if ($differences) {
echo "All Found in array";
} else {
"Not Found !<br>";
}
https://secure.php.net/manual/en/function.array-diff.php

If you would like to stick with in_array you need to loop your terms:
<?php
$terms=array("HELLO","HI","HOWDY");
$row=array("HELLO","HI","Hey");
$chkcond = true;
foreach($row as $needle){
if(!in_array($needle, $terms)){
$chkcond = false;
break;
}
}
if($chkcond){
echo "All Found in Array !<br>";
} else {
echo "Not Found !<br>";
}
?>
Heck re-reading the manual http://php.net/manual/en/function.in-array.php you do not even need to loop:
<?php
$terms=array("HELLO","HI","HOWDY");
$row=array("HELLO","HI","Hey");
if(in_array($row, $terms)){
echo "All Found in Array !<br>";
} else {
echo "Not Found !<br>";
}
?>

Related

how to find multiple comma separated string in main string

I have this main sting.
S,SR,DSR,DS,FX,FXS,SR,DS,S,SR,DS,FX,S,SR,DS,FX,FXS
and i want to find each of the following strings ..
DSR and FXS
i have tried by following code but it can not given me perfect result.
code...
<?php
$mainstring ="S,SR,DSR,DS,FX,FXS,SR,DS,S,SR,DS,FX,S,SR,DS,FX,FXS";
$needed = "DSR,FXS";
if( strpos( $mainstring, $needed ) !== false ) {
echo "Found";
}else{
echo "Not match";
}
?>
One solution would be to explode those strings by comma and verify if the resulted arrays intersection count is the same as your search:
$mainstring ="S,SR,DSR,DS,FX,FXS,SR,DS,S,SR,DS,FX,S,SR,DS,FX,FXS";
$needed = "DSR,FXS";
$mainStringArr = explode(',', $mainstring);
$neededArr = explode(',', $needed);
if (count(array_unique(array_intersect($mainStringArr, $neededArr))) == count($neededArr)) {
echo 'found';
} else {
echo 'not found';
}
Explode the $needed string by command and traverse the array to and compare each value of array into $mainstring using strpos() function. If found then put that value into $arrResut with 'Found' or 'not found' value and finally print the $arrResult to view which value of $needed is found and which is not.
Also, we increment $cntNeeded variable if value if found. at the end of foreach loop compare value of $cntNeeded & $arrNeeded are same then all values are found into $mainstring else not.
$mainstring ="S,SR,DSR,DS,FX,FXS,SR,DS,S,SR,DS,FX,S,SR,DS,FX,FXS";
$needed = "DSR,FXS";
$arrNeeded = explode(",", $needed);
$arrResult = array();
$cntNeeded = 0;
foreach($arrNeeded as $index => $needed) {
if( strpos( $mainstring, $needed ) !== false ) {
$arrResult[$needed] = "Found";
$cntNeeded++;
}
else{
$arrResult[$needed] = "Not match";
}
}
print("<pre> :: arrResult ::");
print_r($arrResult);
print("</pre>");
if($cntNeeded == count($arrNeeded)) {
echo "Found";
}
else {
echo "Not match";
}

Search value "in_array"

I have this array
Array
(
[result] => Array
(
[status] => nok
[reason] => Character not found.
)
[code] => 404
[content_type] => application/json;charset=utf-8
)
I want to check the [status], if it is "nok" it should appear "Match found".
My code:
$info = $r['result']['status'];
if (in_array("nok", $info))
{
echo "Match found";
}
else
{
echo "Match not found";
}
?>
the function in_array check if the value exists in an array, you don't give an array but a string.
You have two options:
change you code to this:
if (isset($r['result']) && in_array("nok", $r['result'])) { //add isset to not raise a warning when it doesn't exists
Or if the result is always the same you can do this:
if (isset($r['result']['status']) && $r['result']['status'] === 'nok') { //add isset to not raise a warning when it doesn't exists
In your case:
$r['result']['status']
is not an array but a string.
So you can ask for:
if(in_array("nok", $r['result']))
or
if($r['result']['status'] == "nok")
$info is not an array, it's a string. Try this instead:
if (in_array("nok", $r['result']))
{
echo "Match found";
}
else
{
echo "Match not found";
}
Or
if ($r['result']['status'] == "nok"){
You don't need to use in_array in this code. in_array searches a linear array for string values... so this is how you would use it:
$arr = array("dog", "cat", "mouse");
if(in_array("mouse", $arr)) echo "Eek, a mouse!";
You can just compare using normal logic since you are comparing a string to a string:
$info = $r['result']['status'];
if ($info == "nok")
{
echo "Match found";
}
else
{
echo "Match not found";
}

PHP Looping through entire multidimensional array but only giving one result back

I have got an multidimensional array on which I run a foreach loop.
I basically want to see if I've got the country_url stored in an database. If it is in the database then I'll echo "exists" but if it doesn't then I want to echo "doesn't exist". I don't want it to tell me for each array if it exists or not, but I want the foreach loop to tell me whether the country_url exists in one of the arrays or not.
foreach ($countriesForContinent as $country) {
if ($country['country_url']==$country_url) {
echo "exists";
} else {
echo "doesn't exist";
}
}
Would anyone be able to help me out with this?
Try this:
$exist = false;
foreach ($countriesForContinent as $country) {
if ($country['country_url']==$country_url) {
$exist = true;
break;
}
}
if ($exist){
echo "exists";
} else {
echo "doesn't exist";
}
You could store a variable and then use break to terminate the loop once the item is found:
$exists = false;
foreach ($countriesForContinent as $country) {
if ($country['country_url']==$country_url) {
$exists = true;
break;
}
}
if ($exists) {
echo "Success!";
}
This should work:
$text = "doesn't exist";
foreach ($countriesForContinent as $country) {
if ($country['country_url']==$country_url) {
$text = "exists";
break;
}
}
echo $text;
As an alternative to the other answers, you could do the following:-
echo (in_array($country_url, array_map(function($v) { return $v['country_url']; }, $countriesForContinent))) ? 'exists' : 'does not exist';
This is probably slightless less efficient though as it will essentially loop through all $countriesForContinent rather than finding a match and break[ing].

How can i make a piece of code run if a foreach loop has not output any values?

I have an array which I have put into a foreach loop, where each value of the array will be outputted to the user. If the user has entered a search query, the value will be checked againast a regex and only be returned if it matches, otherwise the value is just outputted.
The problem I'm having is I havent been able to figure out how to make a conditional "no results found" output if neither the unconditional or the regex conditional outputs output anything. Code below.
foreach ($result as $value)
{
// check to see if query term is set and if so run regex comparison
if (isset($pattern))
{
if (preg_match("/^$pattern/i", $value))
{
echo $value;
echo "<br />";
}
}
// if query is not set, simply output the value
else
{
echo $value;
echo "<br />";
}
// and if there has been no output for either the regex conditional, or other output,
// I want output "no results". How?
}
Before your code snippet add:
if(empty($result)) {
echo 'no results';
} else {
//the rest of your code
}
If I understand correctly this is what you need:
$found = false;
foreach ($result as $value)
{
if (isset($pattern))
{
if (preg_match("/^$pattern/i", $value))
{
$found = true;
echo $value;
echo "<br />";
}
}
// if query is not set, simply output the value
else
{
$found = true;
echo $value;
echo "<br />";
}
}
if($found)
{
echo "Sorry, nothing found.";
}

Error with explode and in_array in php

I would like to check the following condition with php
$string = '10-15~15-20~20-25~';
$stringArray = explode('~',rtrim($string,'~'));
if (in_array('20-25', $stringArray)) {
echo 'Found';
}
else
{
echo 'Not found';
}
20-25 is present in my array but, it always shows not found
There are some errors in your code.
Here is a corrected version.
$string = '10-15~15-20~20-25~';
$stringArray = explode('~',rtrim($string,'~')); // corrected here, missing "$" before "string"
if (in_array('20-25', $stringArray)) { // corrected here, wrong variable name "priceArray"
echo 'Found';
}
else
{
echo 'Not found';
}
replace $priceArray with $stringArray. It's just a typo. You are searching "20-25" in non-initialized variable.

Categories