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

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].

Related

how to use the in_array function, that is storing a variable from an input field

I am trying to check if a value already exists in an array with the in_array function but it is not working. When i assign the $companyalis variable to a string, lets say "Bay" it works. Please how can i solve this issue. Note: the $alias contains a value from an input field.
$companyalis = strtoupper($alias);
if (is_array($responses)) {
$data = [];
foreach ($responses as $val) {
$data[] = $val['alias'];
}
if (in_array($companyalis, $data)) {
echo "Alias is already defined";
}else {
echo "Alias does not exist";
}
}
}
If I understood your question correctly
$companyalis = strtoupper($alias);
if (is_array($responses)) {
$data = [];
foreach ($responses as $val) {
$data[] = $val['alias'];
}
if (in_array($companyalis, array_values($data))) {
echo "Alias is already defined";
} else {
echo "Alias does not exist";
}
}
$aliasList[] = "Other";
$aliasList[] = "manY";
$aliasList[] = "someTime";
$test = "Many";
if(in_array(strtolower($test),array_map('strtolower',$aliasList))) echo "Find";
else echo "Not Find";
I think this code can help you if I understood your question correctly.
The principle is to pass the search string in lowercase as well as all the elements of the array. Via the "strtolower" function applied thanks to "array_map" (thus on the whole array)

in_array fails when using implode in if statement

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

PHP Json only a first result

My issue is that when I use foreach trough my JSON commands it will only give the first command. In this case HELP but not the second one that is Test.
How can I fix this?
PHP:
echo "Commands:<br>";
$json = file_get_contents("App/cmd/commands.json");
$register = json_decode($json, true);
$command = $_GET["c"];
foreach ($register['commands'] as $key => $value){
echo $key;
if($command == $key)
{
echo "Found!";
return;
}
if(isset($register["commands"][$key]["alias"])){
echo " Has Aliases<Br>";
$aliases = explode(",", $register["commands"][$key]["alias"]);
foreach ($aliases as $alias)
{
if($command == $alias)
{
echo "Found!";
return;
}
}
}
echo "Not Found!";
return;
}
My Json:
{"help":"value","commands":{"help":{"function":"test"},"test":{"function":"test"}}}
It is because you set
echo "Not Found!"; return;
in the loop so there is no chance for second iteration. That code should be after loop not inside.
Because you have return; everywhere. Then you can't have a second iteration, because you always finish the process. Remove the return according to your logic to have a second iteration and make proper refactor to your code, to make it functional.

how to search with stristr

i have 2 arrays
$filtered_url_list= array("www.salmat.", "www.webcentral.");
and
$files = array("http://www.salmat.", "http://www.webcentral.", "http://abc.");
i want to search for elements of $filtered_url_list in array $files. If part of the string of $files' elements match then respective $files' string needs to be echoed
my code looks like this
foreach($filtered_url_list as $check_val)
{
$found=FALSE;
foreach($files as $file_val)
{
if(stristr($check_val,$file_val)!==FALSE)
{
$found=TRUE;
}
}
if(!$found)
{
echo $file_val,"\n";
}
}
Example :
www.salmat. is present in http://www.salmat. if this is true then echo http://www.salmat.
My echo statement is incorrect. But i m not getting how to make it correct
Please suggest
Thankyou
Put the echo in the foreach. Also, the order of the arguments for the stristr function is wrong.
foreach($filtered_url_list as $check_val)
{
$found=FALSE;
foreach($files as $file_val)
{
if(stristr($file_val,$check_val)!==FALSE)
{
$found=TRUE;
echo $file_val,"\n";
}
}
}
Try this code:-
foreach($filtered_url_list as $check_val)
{
if(in_array ($check_val ,$contents))
{
//$chcekc_val values is present in $contents array.
}
}
For reference http://php.net/manual/en/function.in-array.php
Use strcmp instead
if(strcmp($check_val,$file_val) ==0)

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

Categories