Check if the variables passed to a function is empty - php

Im working on a register function that will register users into the database.
I want a checker in that function that checks if any of the arguments are empty. I've simplified the problem, so this is not the retail look.
<?php
create_user($_POST["username"], $_POST["epost"]);
function create_user($username, $epost){
// Pull all the arguments in create_user and check if they are empty
// Instead of doing this:
if(empty($username) || empty($epost)){
}
}
Reason for making this is so i can simply add another argument to the function and it checks automatically that it isnt empty.
Shorted question:
How do I check if all the arguments in a function isnt empty?

function create_user($username, $epost){
foreach(func_get_args() as $arg)
{
//.. check the arg
}
}

You can use array_filter and array_map functions also.
For example create a function like below
<?php
function isEmpty( $items, $length ) {
$items = array_map( "trim", $items );
$items = array_filter( $items );
return ( count( $items ) !== (int)$length );
}
?>
the above function accepts two parameters.
$items = array of arguments,
$length = the number of arguments the function accepts.
you can use it like below
<?php
create_user( $_POST["username"], $_POST["epost"] );
function create_user( $username, $epost ) {
if ( isEmpty( func_get_args(), 2 ) ) {
// some arguments are empty
}
}
?>

Related

Use Array data in another function

I am hoping I can get some assistance with some issues I'm trying to get the array data from one function to be used in another function.
So in the function that's creating the array data, it looks like this:
function wlp_generate_pdf_and_save( $data, $post_id ){
// Function needing array data
}
function wlp_generate_preview($data, $generateType){
$out_product_brands = array();
if( count($all_posts) > 0 ){
foreach( $all_posts as $s_post )
{
...
$out_product_brands[] = array( 'brand' => vooHelperNew::get_posts_products( $s_post->ID ) );
...
}
}
}
This function "wlp_generate_preview" works perfectly, but it's this $out_product_brands data i need to use in the function (wlp_generate_pdf_and_save) above this one.
Does the order the functions are place change anything?
Return the data from wlp_generate_preview then pass it as a parameter of wlp_generate_pdf_and_save
First you want to return the array from your first function and then send that as a variable to the second function:
<?php
function wlp_generate_pdf_and_save( $data, $post_id, $input_array ){ //added a third
varible to this functions input
// Function needing array data
}
function wlp_generate_preview($data, $generateType){
$out_product_brands = array();
if( count($all_posts) > 0 ){
foreach( $all_posts as $s_post )
{
...
$out_product_brands[] = array( 'brand' => vooHelperNew::get_posts_products( $s_post->ID ) );
...
}
}
return $out_product_brands;//Returned The array
}
And then when calling your functions you might do something like this:
$input_array = wlp_generate_preview($data, $generateType);//Calls the first function
wlp_generate_pdf_and_save($data, $post_id, $input_array);//The third variable passes it into the next function

PHP - Passing functions with arguments as arguments

I have several interchangeable functions with different numbers of arguments, for example:
function doSomething1($arg1) {
…
}
function doSomething2($arg1, $arg2) {
…
}
I would like to pass a certain number of these functions, complete with arguments, to another handling function, such as:
function doTwoThings($thing1, $thing2) {
$thing1();
$thing2();
}
Obviously this syntax is not correct but I think it gets my point across. The handling function would be called something like this:
doTwoThings(‘doSomething1(‘abc’)’, ‘doSomething2(‘abc’, ‘123’));
So the question is, how is this actually done?
From my research it sounds like I may be able to "wrap" the "doSomething" function calls in an anonymous function, complete with arguments and pass those "wrapped" functions to the "doTwoThings" function, and since the anonymous function doesn't technically have arguments they could be called in the fashion shown above in the second code snippet. The PHP documentation has me confused and none of the examples I'm finding put everything together. Any help would be greatly appreciated!
you could make use of call_user_func_array() which takes a callback (eg a function or class method to run) and the arguments as an array.
http://php.net/manual/en/function.call-user-func-array.php
The func_get_args() means you can feed this funciton and arbitary number of arguments.
http://php.net/manual/en/function.func-get-args.php
domanythings(
array( 'thingonename', array('thing','one','arguments') ),
array( 'thingtwoname', array('thing','two','arguments') )
);
funciton domanythings()
{
$results = array();
foreach( func_get_args() as $thing )
{
// $thing[0] = 'thingonename';
// $thing[1] = array('thing','one','arguments')
if( is_array( $thing ) === true and isset( $thing[0] ) and is_callable( $thing[0] ) )
{
if( isset( $thing[1] ) and is_array( $thing[1] ) )
{
$results[] = call_user_func_array( $thing[0], $thing[1] );
}
else
{
$results[] = call_user_func( $thing[0] );
}
}
else
{
throw new Exception( 'Invalid thing' );
}
}
return $results;
}
This would be the same as doing
thingonename('thing','one','arguments');
thingtwoname('thing','two','arguments');

PHP Parse an arrays values to a function

Ok so I have a function with 2 mandatory arguments and then it must have many optional arguments too.
function example($a,$b, $username, $email) {
// code
}
My data for the optional arguments comes from an array
$x = array('joeblogs', 'joe#blogs.com');
How would i be able to parse these? bearing in mind that the function may be required to parse a different set of arguments each time.
An example is with CakePHP you can specify the action arguments that are required
Something like this?
$a = 'a';
$b = 'b';
$x = array('joeblogs', 'joe#blogs.com');
$args = array_merge(array($a, $b), $x);
call_user_func_array('example', $args);
See http://php.net/manual/en/function.call-user-func-array.php
There are two approaches to optional arguments.
In the first, you specify all of the arguments like this:
function example($a, $b, $c=null, $d=null, $e=null)
Parameters $a and $b are required. The others are optional and are null if nothing is provided. This method requires that each of the optional parameters be specified in the indicated order. If you want to call the method using only $a, $b and $e you have to provide null values for $c and $d:
example($a, $b, null, null, $d);
The second method accepts an array as the third parameter. This array will be checked for keys and processed based on the keys found:
function example($a, $b, $c=array()) {
$optionalParam1 = ( !empty( $c['param1'] ) ) : $c['param1'] ? null;
$optionalParam2 = ( !empty( $c['param2'] ) ) : $c['param2'] ? null;
In this way, you can check for each key that may be provided. Null values will be provided for any key not populated.
Following shows syntax for optional parameters and default values
function example($a,$b, $username = '', $email = '') {
}
Another possibility is to pass an "optional values array"
function example($a,$b, $optional_values = array()) {
if($optional_values[0] != '') { blah blah .... }
}
This solution is a merge of your sugestion and Jez's solution.
call_user_func_array(array($controller, $action), $getVars);
Where $controller is the instance of your controller, $action is the string to the action that you want to call, and $getVars is an array of parameters.
The first parameter of the call_user_func_array function is a callback. It's possible to define a method invocation as callback.
Here is a link to the documentation of PHP's callback: http://www.php.net/manual/pt_BR/language.pseudo-types.php#language.types.callback
To pass the array parameters to a function you can use call_user_func_array:
$args = array( 'foo', 'bar', 'joeblogs', 'joe#blogs.com' );
call_user_func_array( 'example', $args );
Or simple pass any number of parameters:
example( $a, $b, $username, $email );
To retrieve the parameters inside function use func_get_args:
function example() {
$args = func_get_args();
print_r( $args );
// output:
// Array (
// [0] => foo
// [1] => bar
// [2] => joeblogs
// [3] => joe#blogs.com
// )
}

parameter being lossed when passed to array_filter

foreach( $items as $item) {
$taskid = (int) $goal['goal_id'];
$items[$i]['tasks'] = array();
$items[$i]['tasks'] = array_filter($tasks, function($task, $taskid){
return $task['task_id'] == $taskid;
});
Why is $taskid not being passed to the array_filter function, it returns null if echoed from within but if echoed just after it is set it gives the correct value e.g.
foreach( $items as $item) {
$taskid = (int) $goal['goal_id'];
echo $taskid;
Will return whatever the integer is
The return part of the function also works if I manually set a value i.e
return $task['task_id'] == 2;
Guidance appreciated
The issue is variable scope and function arguments.
First, array_filter expects a function with a single argument, that argument is the value in the position in the array. It doesn't handle keys.
You set $taskid = (int) $goal['goal_id']; outside of the anonymous function, and you have a local variable of the same name, which is null because array_filter only passes one argument.
foreach( $items as $item) {
$taskid = (int) $goal['goal_id'];
$items[$i]['tasks'] = array();
# Per the OP, you can pass the necessary variable in via 'use'
$items[$i]['tasks'] = array_filter($tasks, function($task) use($taskid){
return $task['task_id'] == $taskid;
});
}
Thanks guy once you pointed out it was vairiable scope and anonymous functions it was easy enough to fix by referencing in function closure.
$items[$i]['tasks'] = array_filter($tasks, function($task) use(&taskid){
return $task['task_id'] == $taskid;
});
The array_filter function passes in an arrays values into a callback function one-by-one. You cannot pass other parameters in with the anonymous callback function like you are attempting to do.
A valid example would be:
$array = ["Bob","Sam","Jack"];
print_r(
array_filter(
$array,
function($value) {
return ($value !== 'Jack');
}
)
);
Returns
Array ( [0] => Bob [1] => Sam )

How to get a strings data from a different function?

I have a php file with different functions in it. I need to get data from strings in a function, but the strings have been specified in a different function. How can this be done please?
... To clarify, I have two functions.
function a($request) { $username = ...code to get username; }
the username is over retreivable during function a.
function b($request) { }
function b need the username, but cannot retrieve it at the point its called, so need it from function a. I am very much a beginer here (so bear with me please), I tried simply using $username in function b, but that didn't work.
Can you please explain how I can do this more clearly please. There are another 5 strings like this, that function b needs from function a so I will need to do this for all the strings.
...Code:
<?php
class function_passing_variables {
function Settings() {
//function shown just for reference...
$settings = array();
$settings['users_data'] = array( "User Details", "description" );
return $settings;
}
function a( $request ) {
//This is the function that dynamically gets the user's details.
$pparams = array();
if ( !empty( $this->settings['users_details'] ) ) {
$usersdetails = explode( "\n", Tool::RW( $this->settings['users_data'], $request ) );
foreach ( $usersdetails as $chunk ) {
$k = explode( '=', $chunk, 2 );
$kk = trim( $k[0] );
$pparams[$kk] = trim( $k[1] );
}
}
$email=$pparams['data_email'];
$name=$pparams['data_name'];
$username=$pparams['data_username'];
//These variables will retrieve the details
}
function b( $request ) {
//Here is where I need the data from the variables
//$email=$pparams['data_email'];
//$name=$pparams['data_name'];
//$username=$pparams['data_username'];
}
}
?>
#A Smith, let me try to clarify what you mean.
You have several variables, example : $var1, $var2, etc.
You have two function (or more) and need to access that variables.
If that what you mean, so this may will help you :
global $var1,$var2;
function a($params){
global $var1;
$var1 = 1;
}
function b($params){
global $var1,$var2;
if($var1 == 1){
$var2 = 2;
}
}
Just remember to define global whenever you want to access global scope variable accross function. You may READ THIS to make it clear.
EDITED
Now, its clear. Then you can do this :
class function_passing_variables{
// add these lines
var $email = "";
var $name = "";
var $username = "";
// ....
Then in your function a($request) change this :
$email=$pparams['data_email'];
$name=$pparams['data_name'];
$username=$pparams['data_username'];
to :
$this->email=$pparams['data_email'];
$this->name=$pparams['data_name'];
$this->username=$pparams['data_username'];
Now, you can access it in your function b($request) by this :
echo $this->email;
echo $this->name;
echo $this->username;
In the functions where the string has been set:
Global $variable;
$variable = 'string data';
Although you really should be returning the string data to a variable, then passing said variable to the other function.

Categories