1

Can pass a value to specific argument in function ?

function fun1($a,$b)
{
echo $b;
}
@fun1(123);
2
  • in above example...i want to pass 123 value to $b variable in function argument without swapping both variable position. Commented Jul 18, 2012 at 16:04
  • 1
    Like so (null,null,null,null,123); If you ever have to do this: or the function is not designed properly, or it needs built-it checks to allow such "random" use. Commented Jul 18, 2012 at 16:09

4 Answers 4

4

Functions can be defined so that they do not require all parameters. For example:

function foo($a, $b = 2) {
    echo $a + $b;
}

foo(1); //gives 3

Read about default function values here

However, you cannot pass in later parameters without specifying earlier ones. Some simple programming-function-parameters-basics... when you do foo($b) the function has no idea that the variable was named b... It just gets the data; usually a primitive type (in this case an int) or a reference.

You haven't specified how you're using these variables, so you may want to give a dummy value like "-1" to $a (and handle it in your function) (foo(-1, 123)), or rewrite your function so that $a is the second parameter with the default value. (function foo($b, $a = NULL))

That's why you must pass the variables in order; the function assumes you're using it right, and it lines up the values passed with the function definition. function foo($a, $b) means "I'm assuming I should associate your first value with a and your second value with b)".


With your original example function foo($a, $b):

No context, so I would just say do this function foo($b, $a = some_default_value). However, I'm assuming you're using $a and $b equally so you could check to see if it was some default-invalid-value and act on it. However, if your function performs different tasks depending on the (number of) parameters passed, you probably want to separate your function.

If you insist on not switching the order, you could call foo(-1, 123) with a dummy value and check it. Again though, same problem as above


Edit: You've given another example foo($a, $b, $c) and you said you want to do foo($b) to update the middle value. See the explanation in the first paragraph about how a function knows what parameter is what.

If you mean you want to pass an arbitrary set of variables to a function and it knows which ones it got? Again I don't think this is the best practice (you'll need to give us more detail about how you're using this) but you could pass an associative array:

function foo($arr) {
    if (isset($arr['a'])) {
        echo $a;
    }
    if (isset($arr['b'])) {
        echo $b;
    }
    if (isset($arr['c'])) {
        echo $c;
    }
}
foo(array('b' => 123));

I feel horrible after writing this function :P


<?php
function FUN1($a, $b)
{
    echo "HI";
    echo $b;
} //$_a=    123; //error_reporting (E_ALL ^ E_NOTICE ^ E_WARNING); //$b=23; echo @FUN1(123);//it gives HI123 
?>

I formatted your function. Firstly, when I tried that call it doesn't give me "HI123". Secondly, @ is bad practice and really slows down the code. Thirdly, you don't echo FUN1 since it doesn't return anything; your function prints the stuff itself.

You (your student) are/is going in the wrong direction. As I said in my comment, functions already have a beautiful way of sorting out the parameters. Instead of trying to do something funky and work around that, just change your approach.

The example above has no real use and I'm sure in actual code you should just write different functions when you're setting different variables. like setA($a) setB($b) setC($c) setAll($a, $b, $c) and use them accordingly. Arrays are useful for easy variable length functions, but if you're checking each tag to do something, then something's wrong.

Sign up to request clarification or add additional context in comments.

13 Comments

OP precised "without swapping variable positions"
@AlexBelanger I specified another method too. I know he specified that, but he hasn't given us much context and often askers go on irrational preferences. I've had and seen plenty of answers which change the asker's opinion about something
I upvoted back because I did a similar comment but removed it. I think his code is poorly designed, it's not a PHP problem.
Thanks. Yeah it's hard to tell since there isn't any information on how he's using the function/parameters or what he's trying to do. Agree too dummy values lke the function call in your comment are bad, and even worse is the @ in his symbol... I hope he doesn't do that all the time
@drrajgor Then tell her that there's something wrong with her approach and she shouldn't be doing that xD . A function already has it's way of knowing what parameters are passed. Why would you bypass that and come up with your own way of telling a function what's what?
|
1

If you only want to pass one argument, you could make a wrapper function like this:

function PassOne($arg)
{
   fun1(NULL,$arg);
}


function fun1($a,$b)
{
 echo $b;
}

2 Comments

no i am asking a simple question. can we pass a particular value to a specific argument only instedof default argument?
no. When you define the function, it expects all the parameters to be passed. You could pass null however
1

Forgive any inaccuracies. It's been a while since I coded in PHP.

If you want to ensure the order of arguments, you can pass a single array as an argument.

$args = array(
    'name' => 'Robert',
    'ID' => 12345,
    'isAdmin' => true
);

example($args);

function example($args)
{
    echo $args['name']; // prints Robert
    echo $args['ID']; // prints 12345
    echo $args['isAdmin']; // prints true
}

Using this approach, you can also hard-code default values into the function, replacing them only when they're provided in the argument array. Example:

$args = array(
    'name' => 'Robert',
    'ID' => 12345
    // Note that I didn't specify whether Robert was admin or not
);

example($args);

function example($args)
{
    $defaultArgs = array(
        'name' => '',
        'ID' => -1,
        'isAdmin' => false // provides a default value to incomplete requests
    );

    // Create a new, mutable array that's a copy of the default arguments
    $mixArgs = $defaultArgs;

    // replace the default arguments with what was provided
    foreach($args as $k => $v) {
        $mixArgs[$k] = $v;
    }

    /* 
      Now that we have put all the arguments we received into $mixArgs,
      $mixArgs is mix of supplied values and default values.  We can use
      this fact to our advantage:
    */

    echo $mixArgs['name']; // prints Robert

    // if ID is still set to the default value, the user never passed an ID
    if ($mixArgs['ID'] == -1) {
        die('Critical error! No ID supplied!');  // use your imagination
    } else {
        echo mixArgs['ID']; // prints 12345
    }

    echo mixArgs['isAdmin']; // prints false

    // ... etc. etc.
}

2018's PHP syntax and defaults

function example($args=[], $dftArgs=['name'=>'', 'ID' => -1, 'isAdmin'=>false])
{
    if (is_string($args)) 
       $args = json_decode($args,true); // for microservice interoperability
    $args = array_merge($dftArgs,$args); 
    // ... use $args
}
//  PS: $dftArgs as argument is not usual, is only a generalization

1 Comment

This is the correct way, in PHP and Perl5, to "passing value to specific argument" or when you have a lot of parameters. Remember that the function array_merge($defaultParams,$params) is the best way to fix the defaults in this case. Is usual, in microservices implementatios, to use JSON, so $params = json_decode($strJsonParams, true) do the correct casting.
0

No.

But by convention you can skip arguments to built in functions by passing NULL in that position:

fun1(NULL, 123);

Obviously this is doesn't make sense for everything - for example this makes no sense:

$result = strpos(NULL, 'a string');

For user defined functions, it's up to you to handle the arguments in whatever way you see fit - but you might find func_get_arg()/func_get_args() useful for functions that use an indeterminate number of arguments.

Also, don't forget you can make arguments optional by defining default values:

function fun ($arg = 1) {
  echo $arg;
}

fun(2); // 2
fun();  // 1

Note that default values can only be defined on the right-most arguments. You cannot give an argument a default value if an argument to its right does not have one. So this is illegal:

function fun ($arg1 = 1, $arg2) {
  // Do stuff heere
}

4 Comments

thanx alex but is there any other way to pass directly ...like if i have more than 5 argument and i want to pass the 5th one only?
@drrajgor Can you show the specific function you want to do this with?
like passing $b=4 and my function arguments are fun($a,$b,$c) now can we pass fun($b) and it will be store in middle $b variable.?
No. You would have to do fun(NULL, $b);. Can you show the definition of fun()?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.