foreach function only show last value - php

when i wanna get all value to check with current user ip it just check last ip with current user , i don't know why before values doesnt check.
i fill IPs in a textarea like this : 176.227.213.74,176.227.213.78
elseif($maintenance_for == '2') {
$get_ips = $options['ips'];
$explode_ips = explode(',',$get_ips);
foreach ($explode_ips as $ips) {
if($ips == $_SERVER["REMOTE_ADDR"]){
$maintenance_mode = true;
}
else {
$maintenance_mode = false;
}
}
}

If you found the right value, you wan't to BREAK out of the foreach loop
$get_ips = $options['ips'];
$explode_ips = explode(',', $get_ips);
foreach($explode_ips as $ips) {
if ($ips == $_SERVER["REMOTE_ADDR"]) {
$maintenance_mode = true;
break; // If the IP is right, BREAK out of the foreach, leaving $maintenance_mode to true
} else {
$maintenance_mode = false;
}
}

yes, you will always override it. Its better to set a default and only set it once:
(Edit: added #Mathlight's answer, the break, in my solution as he suggested)
$maintenance_mode = false;
foreach ($explode_ips as $ips) {
if($ips == $_SERVER["REMOTE_ADDR"]){
$maintenance_mode = true;
break;
}
}
EDIT : another solution for the record, for the points of a oneliner
$maintenance_mode = in_array($_SERVER["REMOTE_ADDR"], $explode_ips);

Related

PHP Return true in foreach

I want to check if the user is using the default settings. In the example below, I'm trying to check if all "foreached" items return true. If a single foreached item doesn't return true, return false on the whole function.
private function is_using_default_settings() {
// returns a huge array with settings
$merged_preset = $this->options_merged();
foreach($merged_preset as $preset) {
if($preset[5] == 1) {
$section = 'general';
} elseif($preset[5] == 2) {
$section = 'advanced';
} elseif($preset[5] == 3) {
$section = 'technical';
}
$option = get_option($section);
if($preset[3] == $option[$preset[0]] && !is_null($preset[1])) {
return true;
}
}
return false;
}
I've been brainstorming for the past few days to get this sorted on my own, but sadly cannot get it to work. What is the best approach to this?
you can check when is false and block the full foreach then return value, if all is true return value true
try this:
private function is_using_default_settings() {
$returnValue = true;
$merged_preset = $this->options_merged();
foreach($merged_preset as $preset) {
if($preset[5] == 1) {
$section = 'general';
} elseif($preset[5] == 2) {
$section = 'advanced';
} elseif($preset[5] == 3) {
$section = 'technical';
}
$option = get_option($section);
if($preset[3] != $option[$preset[0]] || is_null($preset[1])) {
$returnValue = false;
break;
}
}
return $returnValue;
}
You should return false when any check fails in the foreach, otherwise return true.
function check()
{
foreach($arr as $v)
{
//check fails
if(fail of the check)
return false;
}
return true;
}

Break out of while and skip the following loops

I am looking for an element in multiple while loops, but if the element is found, I don't need to check the following while loops. How can I achieve something like this?
while(something) {
if (this = key) {
// break this loop and skip the next ones. Otherwise proceed to next.
}
}
while(somethingelse) {
if (this = key) {
// break this loop and skip the next ones. Otherwise proceed to next.
}
}
while(somethingthird) {
if (this = key) {
// break this loop and skip the next ones. Otherwise stop looking.
}
}
Use a variable (boolean) that knows if your condition was checked in the previous while, like this:
$breakAll = false; //default false
while(something) {
if (this = key) {
// break this loop and skip the next ones. Otherwise proceed to next.
$breakAll = true; //now break all whiles
}
}
while(somethingelse && !breakAll) {
if (this = key) {
// break this loop and skip the next ones. Otherwise proceed to next.
$breakAll = true; //same here
}
}
while(somethingthird && !breakAll) {
if (this = key) {
// break this loop and skip the next ones. Otherwise stop looking.
}
}
Refactor the while loops to a function and return when the element is found
function doSomething() {
while(something) {
if (this == key) {
return;
}
}
while(somethingelse) {
if (this == key) {
return;
}
}
while(somethingthird) {
if (this == key) {
return;
}
}
}
Use a function
function findSpecificElement($element)
{
while ($something) {
if ($something == $element) {
return $something;
}
}
while ($something) {
if ($something == $element) {
return $something;
}
}
...
}
More correct to use php operator: continue, see:
http://php.net/manual/en/control-structures.continue.php
Example:
while (list($key, $value) = each($arr)) {
if (!($key % 2)) { // skip even members
continue;
}
do_something_odd($value);
}
Operator: break; - break the loop
http://php.net/manual/en/control-structures.break.php
while(something) {
if (this == key) {
break;
}
}
goto can be used in a situation like this to jump over the while loops that should not be run.
while(something) {
if (this = key) {
goto yourDoom; // Breaks out of loop and goes to label "yourDoom"
}
}
while(somethingelse) {
if (this = key) {
goto yourDoom; // Breaks out of loop and goes to label "yourDoom"
}
}
while(somethingthird) {
if (this = key) {
goto yourDoom; // Breaks out of loop and goes to label "yourDoom"
}
}
yourDoom: // This is a label that you can go to
// Do something

Is it possible to create a for loop inside an if condition?

I need to check if some text areas are set, but there might be a lot of them. I want to check if every single one of them is set inside an if statement with a for loop.
if(//for loop here checking isset($_POST['item'.$i]) )
You could do this:
// Assume all set
$allSet = true;
// Check however many you need
for($i=0;$i<10;$i++) {
if (!isset($_POST['item'.$i])) {
$allSet=false; // If anything is not set, flag it and bail out.
break;
}
}
if ($allSet) {
//do stuff
} else {
// do other stuff
}
If you've only a few, or they're not sequential there's no need for a loop. You can just do:
if (isset($_POST['a'], $_POST['d'], $_POST['k']....)) {
// do stuff if everything is set
} else {
// do stuff if anything is not set
}
try using this:
$post=$_POST;
foreach($post as $key=>$value){
if (isset($value) && $value !="") {
// do stuff if everything is set
} else {
// do stuff if anything is not set
}
You can try:
<?php
$isset = true;
$itemCount = 10;
for($i = 0; $i < $itemCount && $isset; $i++){
$isset = isset($_POST['item'.$i]);
}
if ($isset){
//All the items are set
} else {
//Some items are not set
}
I'm surprised that after three answers, there isn't a correct one. It should be:
$success = true;
for($i = 0; $i < 10; $i++)
{
if (!isset($_POST['item'.$i]))
{
$success = false;
break;
}
}
if ($success)
{
... do something ...
}
Many variation are possible, but you can really break after one positive.
Yes, one may have a loop within an if-condtional. You may use a for-loop or you may find it more convenient to use a foreach-loop, as follows:
<?php
if (isset($_POST) && $_POST != NULL ){
foreach ($_POST as $key => $value) {
// perform validation of each item
}
}
?>
The if conditional basically tests that a form was submitted. It does not prevent an empty form from being submitted, which means that any required data must be checked to verify that the user provided the information. Note that $key bears the name of each field as the loop iterates.

PHP foreach loop JSON

I know there are like hundreds similar questions on this site, but I just can't get my code working...
I have this JSON
{
"version":"1.0.0",
"buildDate":20131029,
"buildTime":165127,
"lockPath":"..\\var\\lock",
"scriptPath":"..\\var\\lock",
"connections":
[
{
"name":"o016561",
"bez":"GEW-NRW",
"type":"OVPN"
},
{
"name":"o016482",
"bez":"GEW-BW",
"type":"OVPN"
},
{
"name":"o019998",
"bez":"GEW-SH",
"type":"OVPN"
}
]}
how can I access the "name" values to check if there's an existing file with an equal name?
I tried
$json_config_data = json_decode(file_get_contents($json_path,true));
foreach($json_config_data->connections as $connectionName)
{
if($connectionName->name == $fileName)
{
$status = 1;
}
else
{
$status = 0;
}
}
but I always get $status = 0...
I think there's an easy solution for this, but I'm pretty new to PHP so I'd be glad for any kind of help.
Thanks in advice
You're resetting the value of $status for every iteration which means that the last connection HAS to be the correct one. You're probably looking for a break statement.
$json_config_data = json_decode(file_get_contents($json_path,true));
$status = 0; //Default to 0
foreach($json_config_data->connections as $connectionName)
{
if($connectionName->name == $fileName)
{
$status = 1;
break; //End the loop
}
}
This would only result in $status == 1 if the final name matched your requirements; otherwise you're setting $status back to 0. You should break out of the loop when you find a match:
$status = 0;
foreach ($json_config_data->connections as $connectionName) {
if ($connectionName->name == $fileName) {
$status = 1;
break; // this breaks out of the foreach loop
}
}

I need a more efficient way of checking if multiple $_POST parameters isset

I have these variables, and I need to check if all of them isset(). I feel there has to be a more efficient way of checking them rather than one at a time.
$jdmMethod = $_POST['jdmMethod'];
$cmdMethod = $_POST['cmdMethod'];
$vbsMethod = $_POST['vbsMethod'];
$blankPage = $_POST['blankPage'];
$facebook = $_POST['facebook'];
$tinychat = $_POST['tinychat'];
$runescape = $_POST['runescape'];
$fileUrl = escapeshellcmd($_POST['fileUrl']);
$redirectUrl = escapeshellcmd($_POST['redirectUrl']);
$fileName = escapeshellcmd($_POST['fileName']);
$appData = $_POST['appData'];
$tempData = $_POST['tempData'];
$userProfile = $_POST['userProfile'];
$userName = $_POST['userName'];
Try this
$allOk = true;
$checkVars = array('param', 'param2', …);
foreach($checkVars as $checkVar) {
if(!isset($_POST[$checkVar]) OR !$_POST[$checkVar]) {
$allOk = false;
// break; // if you wish to break the loop
}
}
if(!$allOk) {
// error handling here
}
I like to use a function like this:
// $k is the key
// $d is a default value if it's not set
// $filter is a call back function name for filtering
function check_post($k, $d = false, $filter = false){
$v = array_key_exists($_POST[$k]) ? $_POST[$k] : $d;
return $filter !== false ? call_user_func($filter,$v) : $v;
}
$keys = array("jdmMethod", array("fileUrl", "escapeshellcmd"));
$values = array();
foreach($keys as $k){
if(is_array($k)){
$values[$k[0]] = check_post($k[0],false,$k[1]);
}else{
$values[$k] = check_post($k[0]);
}
}
You could extend the keys array to contain a different default value for each post-value if you wish.
EDIT:
If you want to make sure all of these have a non-default value you could do something like:
if(sizeof(array_filter($values)) == sizeof($keys)){
// Not all of the values are set
}
Something like this:
$jdmMethod = isset($_POST['jdmMethod']) ? $_POST['jdmMethod'] : NULL;
It's Ternary Operator.
I think this should work (not tested, from memory)
function handleEmpty($a, $b) {
if ($b === null) {
return false;
} else {
return true;
}
array_reduce($_POST, "handleEmpty");
Not really. You could make a list of expected fields:
$expected = array(
'jdmMethod',
'cmdMethod',
'fileName'
); // etc...
... then loop those and make sure all the keys are in place.
$valid = true;
foreach ($expected as $ex) {
if (!array_key_exists($ex, $_POST)) {
$valid = false;
break;
}
$_POST[$ex] = sanitize($_POST[$ex]);
}
if (!$valid) {
// handle the problem
}
If you can develop a generic sanitize function, that will help - you can just sanitize each as you loop.
Another thing I like to use is function that gives a default as it sanitizes.
function checkParam($key = false, $default = null, $type = false) {
if ($key === false)
return $default;
$found_option = null;
if (array_key_exists($key,$_REQUEST))
$found_option = $_REQUEST[$key];
if (is_null($found_option))
$found_option = $default;
if ($type !== false) {
if ($type == 'string' && !is_string($found_option))
return $default;
if ($type == 'numeric' && !is_numeric($found_option))
return $default;
if ($type == 'object' && !is_object($found_option))
return $default;
if ($type == 'array' && !is_array($found_option))
return $default;
}
return sanitize($found_option);
}
When a default is possible, you'd not want to do a loop, but rather check for each independently:
$facebook = checkParam('facebook', 'no-facebook', 'string);
It is not the answer you are looking for, but no.
You can create an array an loop through that array to check for a value, but it doesn't get any better than that.
Example:
$postValues = array("appData","tempData",... etc);
foreach($postedValues as $postedValue){
if(isset($_POST[$postedValue])){
...
}
}

Categories