PHP Json only a first result - php

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.

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)

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

Delete element from array if not found

I have some code I created which is supposed to see if something exists in an array of strings. If it does not exist, I want to delete that element of the array. I thought we do this with unset, but it doesnt seem to be working. Mind helping?
echo '<br>size of $games before end-check: '.sizeof($games);
foreach ($games as $game) {
$game_end_marker = "body = (game)#";
$game_end_pos = strpos($game, $game_end_marker);
if ($game_end_pos !== false) {
echo "<br>end of game found";
}
else {
echo "<br>end of game not found. incomplete game";
unset($game);
}
}
echo '<br>size of $games after end-check: '.sizeof($games);
output:
size of $games before end-check: 2
end of game found
end of game not found. incomplete game
size of $games after end-check: 2
Because you unset the variable $game, not the element in the array. Try this:
echo '<br>size of $games before end-check: '.sizeof($games);
foreach ($games as $index => $game) {
$game_end_marker = "body = (game)#";
$game_end_pos = strpos($game, $game_end_marker);
if ($game_end_pos !== false) {
echo "<br>end of game found";
}
else {
echo "<br>end of game not found. incomplete game";
unset($games[$index]);
}
}
echo '<br>size of $games after end-check: '.sizeof($games);
You have to unset the index of game.
foreach ($games as $key => $value) {
// all your logic here, performed on $value
unset($games[$key]);
}
This merely unsets your local reference to the element. You need to be referring directly to the array.
foreach($games as $key => $game)
unset($games[$key]);
That won't work: foreach creates a new variable, copying the old one. Unsetting it will do nothing to the original value. Likewise, making it a reference won't work either, since only the reference would be deleted.
The nicest way to do this would be with array_filter:
$games = array_filter($games, function($game) {
$game_end_marker = "body = (game)#";
$game_end_pos = strpos($game, $game_end_marker);
if ($game_end_pos !== false) {
echo "<br>end of game found";
return true;
}
else {
echo "<br>end of game not found. incomplete game";
return false;
}
});
This uses the anonymous function syntax introduced in PHP 5.3. If the function returns true, the element is kept; if it returns false, the element is removed.
You can also call by reference:
foreach($games as &$game) {
unset($game);
}
In this way you can also change $game (eg. $game .= " blah";) and the original array will be modified.
You can use array_splice in conjunction with an incrementally-increasing index variable to remove the current item from the array:
$index = 0;
foreach ($games as $game) {
$game_end_marker = "body = (game)#";
$game_end_pos = strpos($game, $game_end_marker);
if ($game_end_pos !== false) {
echo "<br>end of game found";
}
else {
echo "<br>end of game not found. incomplete game";
array_splice($games, $index, 1);
}
$index++;
}

PHP Array foreach question

I have a question about arrays and foreach.
If i have an array like this:
$test_arr = array();
$test_arr['name1'] = "an example sentence";
$test_arr['anything'] = "dsfasfasgsdfg";
$test_arr['code'] = "4334refwewe";
$test_arr['empty1'] = "";
$test_arr['3242'] = "";
how can I do a foreach and "pick" only the ones that have values? (in my array example, would only take the first 3 ones, name1, anything and code).
I tried with
foreach ($test_arr as $test) {
if (strlen($test >= 1)) {
echo $test . "<br>";
}
}
but it doesn't work. Without the "if" condition it works, but empty array values are taken into consideration and I don't want that (because I need to do a <br> after each value and I don't want a <br> if there is no value)
Sorry if I don't explain myself very well, I hope you understand my point. Shouldn't be too difficult I guess..
Thanks for your help !
Maybe will work
foreach ($test_arr as $test) {
if (strlen($test)!=="") {
echo $test . "<br>";
}
}
Your solution with corrected syntax:
foreach ($test_arr as $test) {
if (strlen($test)>=1) {
echo $test . "<br>";
}
}
Since empty strings are false, you could just do this (but you'd exclude 0's with the if):
foreach ($test_arr as $key => $val) {
if ($val) {
echo $val. "<br>";
}
}
If it has to be an empty string then (excluding 0 and FALSE):
foreach ($test_arr as $key => $val) {
// the extra = means that this will only return true for strings.
if ($val !== '' ) {
echo $val. "<br>";
}
}
Since it looks like you're using an associative array, you should be able to do this:
foreach( $test_arr as $key => $value )
{
if( $value != "" )
{
echo $value . "<br />";
}
}
As shown, you can test $value for an empty string directly. Since this is precisely the test you are trying to accomplish, I would hope that this would solve your problem perfectly.
On another note, this is pretty straight forward and should be very maintainable in the future when you've forgotten exactly what it was that you were doing!
You are better off to use a while loop like this:
while(list($test_key, $test_value) = each($test_arr))
{
if($test_value != "") { echo $test_value . "<br/>"; }
}
reset($test_arr);
If your array gets large, the while will be much faster. Even on small arrays, I have noticed a big difference in the execution time.
And if you really don't want the array key. You can just do this:
while(list(, $test_value) = each($test_arr))
{
if($test_value != "") { echo $test_value . "<br/>"; }
}
reset($test_arr);
You can check if the value is emtpy with empty().
Note that values like 0 or false are considered empty as well, so you might have to check for string length instead.
just a simple typing error:
foreach ($test_arr as $test) {
if (strlen($test) >= 1) {
echo $test . "<br>";
}
}
Try this:
foreach ($test_arr as $test) {
if (strlen($test) > 0) {
echo $test . "<br>";
}
}

Categories