Solved

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

Posted on 2015-01-16
16
55 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 6
  • 2
16 Comments
 
LVL 8

Expert Comment

by:Ahmed Merghani
ID: 40554065
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
ID: 40554379
Yes but I was wondering if it was possible like

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

Expert Comment

by:Ahmed Merghani
ID: 40554853
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
Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

 
LVL 110

Expert Comment

by:Ray Paseur
ID: 40555044
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
ID: 40555069
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 110

Expert Comment

by:Ray Paseur
ID: 40555075
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
ID: 40555083
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 110

Expert Comment

by:Ray Paseur
ID: 40555085
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
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 40555092
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
ID: 40555748
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 110

Expert Comment

by:Ray Paseur
ID: 40556092
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
ID: 40556214
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 110

Expert Comment

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

Author Comment

by:Mark
ID: 40556228
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
ID: 40556233
I know but I was nagging me how to exit the function within a short-circuit format.
0
 

Author Closing Comment

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

Featured Post

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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 i…
This article discusses how to create an extensible mechanism for linked drop downs.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

710 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