Is there any possibility to break a loop while calling a function? - php

Let's say I have a simple code:
while(1) {
myend();
}
function myend() {
echo rand(0,10);
echo "<br>";
if(rand(0,10) < 3) break;
}
This will not work with error code 'Fatal error: Cannot break/continue 1 level on line'.
So is there any possibility to terminate the loop during a subfunctin execution?

Make the loop condition depend upon the return value of the function:
$continue = true;
while( $continue) {
$continue = myend();
}
Then, change your function to be something like:
function myend() {
echo rand(0,10);
echo "<br>";
return (rand(0,10) < 3) ? false : true;
}

There isn't. Not should there be; if your function is called somewhere where you're not in a loop, your code will stop dead. In the example above, your calling code should check the return of the function and then decide whether to stop looping itself. For example:
while(1) {
if (myend())
break;
}
function myend() {
echo rand(0,10);
echo "<br>";
return rand(0,10) < 3;
}

Use:
$cond = true;
while($cond) {
$cond = myend();
}
function myend() {
echo rand(0,10);
echo "<br>";
if(rand(0,10) < 3) return false;
}

Related

Use return in php function with if statement

Is there a way to use return in a function with an if statement?
I would like to see either the function was executed until the if statement or not.
This would help me to check if the sql query would be executed as well.
I know to 100% I only could check it on the sql response, but I am looking for the shortest way to figure out if the content of a function was executed or not.
Here is an example:
<?php
function hi($i)
{
return (1==$i){echo "Hello"; };
}
$i = '1';
echo hi($i);
?>
I try to avoid to use it like this, since I always require to add an return before the end of the if statement:
<?php
function hi($i)
{
if(1==$i){
echo "Hello";
};
return true;
}
$i = '1';
echo hi($i);
?>
<?php
function ifReturn($input){
$message="";
if ($input == 3){
$message ="input is 3";
} else {
$message = "input is everything BUT 3";
}
return $message;
}
echo '<p>'.ifReturn(3).'</p>';
echo '<p>'.ifReturn(2).'</p>';

if else if condition not working properly

Test.php
<?php
$a = 'D:/mydomain/Slim/Lib/Table.php';
$b = '\Slim\Lib\Table';
foreach (array($a, $b) as $value)
{
if (file_exists($value))
{
echo "file_exist";
include_once($value);
new Table();
}
else if (class_exists($value))
{
echo "class_exist";
$class = new $value();
}
else
{
echo "error";
}
}
?>
and D:/mydomain/Slim/Lib/Table.php
<?php
class Table {
function hello()
{
echo "test";
}
function justTest()
{
echo "just test";
}
}
?>
When im execute test.php in browser the output result is:
file_exist
Fatal error: Cannot redeclare class Table in D:/mydomain/Slim/Lib/Table.php on line 2
if statement for class_exist is not trigger. namespace \Slim\Lib\Table is never exist.
The second, optional, parameter of class_exists is bool $autoload = true, so it tries to autoload this class. Try to change this call to class_exists( $value, false) See the manual.
The first if can be changed to:
if(!class_exists($value) && file_exists($file)
actually there are other problems:
$a = 'D:/mydomain/Slim/Lib/Table.php';
$b = 'Table'; //Since you don't have a namespace in the Table class...
//This ensures that the class and table are a pair and not checked twice
foreach (array($a=>$b) as $file=>$value)
{
if (!class_exists($value) && file_exists($file))
{
echo "file_exist";
include_once($file);
$class = new $value();
}
else if (class_exists($value))
{
echo "class_exist";
$class = new $value();
}
else
{
echo "error";
}
}

Checking for undefined variables in a function php

So I've been trying to devise a function that will echo a session variable only if it is set, so that it wont create the 'Notice' about an undefined variable. I am aware that one could use:
if(isset($_SESSION['i'])){ echo $_SESSION['i'];}
But it starts to get a bit messy when there are loads (As you may have guessed, it's for bringing data back into a form ... For whatever reason). Some of my values are also only required to be echoed back if it equals something, echo something else which makes it even more messy:
if(isset($_SESSION['i'])){if($_SESSION['i']=='value'){ echo 'Something';}}
So to try and be lazy, and tidy things up, I have tried making these functions:
function ifsetecho($variable) {
if(!empty($variable)) {
echo $variable;
}
}
function ifseteqecho($variable,$eq,$output) {
if(isset($variable)) {
if($variable==$eq) {
echo $output;
}
}
}
Which wont work, because for it to go through the function, the variable has to be declared ...
Has anyone found a way to make something similar to this work?
maybe you can achieve this with a foreach?
foreach ($_SESSION as $variable)
{function ifseteqecho($variable,$eq,$output) {
if($variable==$eq) {
echo $output;
}
else echo $variable;
}
}
now this will all check for the same $eq, but with an array of corresponding $eq to $variables:
$equiv = array
('1'=>'foo',
'blue'=>'bar',);
you can check them all:
foreach ($_SESSION as $variable)
{function ifseteqecho($variable,$equiv) {
if(isset($equiv[$variable])) {
echo $equiv[$variable];
}
else {
echo $variable;
}
}
}
Something like this?, you could extend it to fit your precise needs...
function echoIfSet($varName, array $fromArray=null){
if(isset($fromArray)){
if(isset($fromArray[$varName])&&!empty($fromArray[$varName])){
echo $fromArray[$varName];
}
}elseif(isset($$varName)&&!empty($$varName)){
echo $$varName;
}
}
You may use variable variables:
$cat = "beautiful";
$dog = "lovely";
function ifsetecho($variable) {
global $$variable;
if(!empty($$variable)){
echo $$variable;
}
}
ifsetecho("cat");
echo "<br/>";
ifsetecho("dog");
echo "<br/>";
ifsetecho("elephant");
UPDATE: With a rather complex code I’ve managed to meet your requirements:
session_start();
$cat = "beautiful";
$dog = "lovely";
$_SESSION['person']['fname'] = "Irene";
function ifsetecho($variable){
$pattern = "/([_a-zA-Z][_a-zA-Z0-9]+)".str_repeat("(?:\\['([_a-zA-Z0-9]+)'\\])?", 6)."/";
if(preg_match($pattern, $variable, $matches)){
global ${$matches[1]};
if(empty(${$matches[1]})){
return false;
}
$plush = ${$matches[1]};
for($i = 2; $i < sizeof($matches); $i++){
if(empty($plush[$matches[$i]])){
return false;
}
$plush = $plush[$matches[$i]];
}
echo $plush;
return true;
}
return false;
}
ifsetecho("cat");
echo "<br/>";
ifsetecho("dog");
echo "<br/>";
ifsetecho("elephant");
echo "<br/>";
ifsetecho("_SESSION['person']['fname']");
echo "<br/>";
ifsetecho("_SESSION['person']['uname']");
echo "<br/>";

Return false does not allow echo

Following is my code in which i am facing only one difficulty that when i run the following script then due to comparison failure the $flag doesnot echo kindly let me know how to fix this?
$s = "iph4on comes";
$se = "4gb comes in iphone";
$f = 0;
$tf = explode(" ",$searching);
$ms= explode(" ",$search_in);
foreach($tf as $word)
{
if (!preg_match("/$word/i", $search_in))
//if (!strpos($search_in, $word));
return false;
}
{
$f = 1;
}
echo $f;
//Due to return flase above i am not echoing
echo "Comparison Failed";
return terminates the currently executing code block and "returns" to whatever called that code. if you execute a return in the top level of the code, it's essentially an exit() call and your echo will never be reached.
Why not just put an echo $flag before the return statement?
if (!preg_match("/$word/i", $search_in)){
echo $flag
return false;
}
You need to put the echo before the return. return gets the execution back to the calling function, hence any code after that won't be executed.
if (!preg_match("/$word/i", $search_in)) {
$flag = 1;
echo $flag;
echo "Comparison Failed";
return false;
}

Skip parent if using PHP

Not sure if this is even possible, but the basic idea of the code is as follows:
if(isset($_POST['submit'])) {
if($_POST['field'] == 0) {
// do not process the code in the if statement
}
// code to process if the above validation criteria is not met
}
I basically want to try and keep it as simple as possible without lots of if's everywhere, just the quick validation statements at the top, and if none of those if statements are triggered, it will process the code to update the database etc.
I have tried the continue statement function with no joy, I believe that only works with loops.
Thanks!
if(isset($_POST['submit']) && $_POST['field'] != 0) {
}
As a function
function testCondition() {
return isset($_POST['submit']) &&
$_POST['field'] != 0;
}
if (testCondition()) { ... }
You could put all of this in a function and then call 'return' from the inside 'if':
if(isset($_POST['submit']) && validate_form())
{
...
}
function validate_form()
{
if($_POST['field'] == 0) {
return false;
}
if(another check that fails) {
return false;
}
...
return true;
}
To accomplish this as you originally desired, you need to use the break statement. From the PHP manual:
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
if ($val == 'stop') {
break; /* You could also write 'break 1;' here. */
}
echo "$val<br />\n";
}
/* Using the optional argument. */
$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "At 5<br />\n";
break 1; /* Exit only the switch. */
case 10:
echo "At 10; quitting<br />\n";
break 2; /* Exit the switch and the while. */
default:
break;
}
}

Categories