0

in php func_get_args — Returns an array comprising a function's argument list

it returns numeric index array

is there any function/way in php by which we get associative array i.e. key=>value pair

i m explaining with example:

###test.php

<?php

function foo() {
    include './fga.inc';
}
$x=20;
$y=30;

foo($x, $y);
?>

###fga.inc

<?php

$args = func_get_args();
echo "<pre>";
print_r($args);
echo "</pre>";

?>

which should returns

array (
  'x'=> 20,
  'y' => 30,
)

1 Answer 1

3

You can't do this within your foo() function, because PHP doesn't pass the variable names to your function, only their values. Plus, PHP doesn't support named arguments in functions, and it doesn't seem like it'll do so anytime soon.

A workaround would be to pass an associative array as a single argument to your function. You can use compact() to collate the variables in the calling scope that you want to pass, for example:

function foo($args) {
    echo "<pre>";
    print_r($args);
    echo "</pre>";
}

$x = 20;
$y = 30;

foo(compact('x', 'y'));

Output:

Array
(
    [x] => 20
    [y] => 30
)
Sign up to request clarification or add additional context in comments.

Comments

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.