Solved

Returning from function if variable is false (in short circuit)

Posted on 2015-01-16
16
42 Views
Last Modified: 2015-01-23
Example:
function test($options) {
		$options = array(
								'clientid' => 					$options['clientid'] || return false,
								'format' =>						$options['format'] || 'text',
								'citiesMaxLen' =>				$options['citiesMaxLen'] || 1000,
								'ShowApptScheduledTimeOnly' =>	$options['ShowApptScheduledTimeOnly'] || false,
								'skipApptTime' =>				$options['skipApptTime'] || false,
								'divisionsToBR' =>				$options['divisionsToBR'] || false			
						);

	echo 'past';
						
}

Open in new window


If client id is false, can I return from the variable or do I have to perform an if or check ...
0
Comment
Question by:Mark
  • 8
  • 6
  • 2
16 Comments
 
LVL 8

Expert Comment

by:Ahmed Merghani
Comment Utility
Hi,
You can do it like this:
$options = array(
								'clientid' => 					(isset($options['clientid']) ? $options['clientid'] : false),
								'format' =>						(isset($options['format']) ? $options['format'] : 'text'),
								'citiesMaxLen' =>				(isset($options['citiesMaxLen']) ? $options['citiesMaxLen'] : 1000),
								'ShowApptScheduledTimeOnly' =>	(isset($options['ShowApptScheduledTimeOnly']) ? $options['ShowApptScheduledTimeOnly'] : false),
								'skipApptTime' =>				(isset($options['skipApptTime']) ? $options['skipApptTime'] : false),
								'divisionsToBR' =>				(isset($options['divisionsToBR']) ? $options['divisionsToBR'] : false)			
						);

Open in new window

0
 

Author Comment

by:Mark
Comment Utility
Yes but I was wondering if it was possible like

TheFunction({a => 123})
0
 
LVL 8

Expert Comment

by:Ahmed Merghani
Comment Utility
Yes you can with this modified code:
function test($options) {
	$options = array(
		'clientid' => 					(isset($options['clientid']) ? $options['clientid'] : false),
		'format' =>						(isset($options['format']) ? $options['format'] : 'text'),
		'citiesMaxLen' =>				(isset($options['citiesMaxLen']) ? $options['citiesMaxLen'] : 1000),
		'ShowApptScheduledTimeOnly' =>	(isset($options['ShowApptScheduledTimeOnly']) ? $options['ShowApptScheduledTimeOnly'] : false),
		'skipApptTime' =>				(isset($options['skipApptTime']) ? $options['skipApptTime'] : false),
		'divisionsToBR' =>				(isset($options['divisionsToBR']) ? $options['divisionsToBR'] : false)			
	);
	echo 'past';						
}

Open in new window

Then you can call it with this:
test($ary)

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
The basic syntax of PHP is pretty loose and it may tolerate something like what's written here, but to my eye the intent of the code is confusing and could probably be refactored to make it more fluent.  Have a look at the comments in this code snippet below.  It seems like the thing you want to learn about is PHP variable scope.

<?php
/**
 * This is a function definition.  Functions encapsulate variables.  
 * The way you get information (dependencies) into a function is to pass the
 * dependencies in through the function call.  This is called dependency injection.
 *
 * In the example below, we inject the $options variable into our test() function.
 * The injection makes a copy of the $options variable and makes it available to
 * the code inside the function.  The original $options variable is not changed
 * by the code inside the function.
 */
function test($options)
{
    /**
     * Inside the function, we can refer to the injected dependencies by using 
     * the same name that was used in the function definition.  As a result of 
     * this code, whatever data was passed to the function in $options has now
     * been overwritten by the assignment statement.  This overwritten data is
     * only present inside the function definition.
     */
    $options = array( /* stuff here */ );

    /**
     * After the function has run, it has assigned data to variables inside the
     * function scope, but these variables are not available outside of the 
     * function, except via GLOBAL (a bad idea) or RETURN (a good idea). To get the 
     * data out of the function, you can return one (and only  one) variable.  The
     * returned variable may be any data type, including arrays and objects.
     */
    $something_created_inside_the_function = 'Hello World';
    return $something_created_inside_the_function;
}

/** 
 * This is the use of the function that was defined above. Whatever we pass
 * in via dependency injection can be acted upon inside the function, and 
 * whatever data is constructed inside the function can be returned to
 * the calling "scope."  In this case the script will say "Hello World."
 */
$x = test();
echo $x;

Open in new window

Refs:
http://php.net/manual/en/language.variables.scope.php
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_12310-PHP-Variables-and-References.html
0
 

Author Comment

by:Mark
Comment Utility
Let me clarify... I want to exit the function if $options['clientid'] is false however because I may have 1000 variables to check over (1000 elements/values in an array), I want to do it while I am going over the array passed into the function (not with a bunch of if statements or using an additional fixed array that defines default values and doing a foreach loop...

            $options = array(      'clientid' =>                               $options['clientid'] || return false, ......
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
PHP uses loose data typing, so the meanings of TRUE and FALSE may be blurred by values that are truthy or falsy.  Do you want to exit the function if any of the array elements evaluate to FALSE?
0
 

Author Comment

by:Mark
Comment Utility
No, just specific ones ... I was checking like this hoping I could pass a function it which will exit the function but couldn't

'Clientid' => $options['clientid'] ? $options['clientid'] : return false,
'Nextelement' ....
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Yes, I think the ternary operator may be helpful here.  I'll see if I can come up with a code sample.
http://php.net/manual/en/language.operators.php
http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
See if this makes sense.  After I started writing the code, I couldn't come up with a sensible way to use the ternary notation.  The design here says, "Give me two arrays, one of data and one of signal keys.  If the data at any signal key location meets some test (in this case contains FALSE) then return FALSE from the function.  Otherwise return TRUE."
http://iconoun.com/demo/temp_mark.php

<?php // demo/temp_mark.php
error_reporting(E_ALL);
echo '<pre>';


// DEFINE OUR FUNCTION AND THE VALUES WE WANT TO TEST
function mything(array $collection, array $signals=[])
{
    // TEST THE SIGNAL VALUES
    foreach ($signals as $signal)
    {
        if ($collection[$signal] === FALSE) return FALSE;
    }

    // IF WE GET HERE, NONE OF THE SIGNAL VALUES ARE FALSE
    return TRUE;
}


// SOME TESTS TO ILLUSTRATE THE PRINCIPLES
$data = array
( 'A' => FALSE
, 'B' => 2
, 'C' => 3
, 'D' => FALSE
)
;

// TESTING WITH AN EMPTY SIGNAL ARRAY
$w = mything($data);
echo PHP_EOL . "VALUE OF w IS ";
var_dump($w);


// TESTING WITH A POPULATED SIGNAL ARRAY
$x = mything($data, ['B', 'C', 'D']);
echo PHP_EOL . "VALUE OF x IS ";
var_dump($x);

$y = mything($data, ['A']);
echo PHP_EOL . "VALUE OF y IS ";
var_dump($y);

$q = array('B', 'C');
$z = mything($data, $q);
echo PHP_EOL . "VALUE OF z IS ";
var_dump($z);

Open in new window

0
 

Accepted Solution

by:
Mark earned 0 total points
Comment Utility
That solution still requires an additional array of rules ... What about this

function .....

      $options = array(
            'clientid' =>                               $options['clientid'] ? $options['clientid'] : '!exit!'
);

foreach ($options AS $a => $b) {
If($b=='!exit!') return false
}

Now I just need a value instead of !exit! That would be highly unlikely to be the intended original value

With this I can have hundreds of pairs in the array and not have to write if statements again for each one
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
I believe that any solution is going to require an "array of rules" since it sounds like you're engaged in building some kind of filter.  There are known design patterns for these things.  Suggestion:  Please show us a good and representative test data set, some sort of SSCCE that gives your expected inputs and outputs.  Armed with that information I'm sure I can show you a workable design.

I'm asking for this because as a professional programmer, in my experience an economy of code is sometimes a desirable thing, but an easy-to-understand design is always a desirable thing.  It may be smarter to write the application a little differently and it will be easier to know for sure if we can see the existing data and the expected results.

Thanks, ~Ray
0
 

Author Comment

by:Mark
Comment Utility
I'm simply building a function to lookup a record and return it in a formatted manner. The only parameter that is needed is CLientID. I was just interested for the next time I write a function with multiple arguments how to best go about it.

If it was a more advanced function I would definitely agree on having a ruleset but in this instance I think I will stick with my aforementioned solution.

Thank you for everybody's assistance.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
The only parameter that is needed is CLientID.
In that case you need only one if() statement!
0
 

Author Comment

by:Mark
Comment Utility
An alternative and more bulletproof solution is to name the variable with the rule set, example ..

'ClientID___INTRequired'

Then loop through the array and if any elements have INTRequired at the end of their name and they don't contain an integer, return false.
0
 

Author Comment

by:Mark
Comment Utility
I know but I was nagging me how to exit the function within a short-circuit format.
0
 

Author Closing Comment

by:Mark
Comment Utility
It is the solution I was seeking however it didn't occur to me till after I posted the question.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Both Easy and Powerful How easy is PHP? http://lmgtfy.com?q=how+easy+is+php (http://lmgtfy.com?q=how+easy+is+php)  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now