PHP extract values from an array and pass them to a function - php

I'm trying to extract values from an array, and pass them to a function where they'll be used. I've used echo inside the function for this example.
I'm using extract to get all the values.
Thing is, this wont work. Do you see how this can be done?
<?php
$my_array = array("a" => "Prince", "b" => "Funky"); // around 10 more
$g = extract($my_array);
foo($g);
function foo($g) {
echo 'My name is '.$a.', and I am '.$b;
}
?>

Functions in PHP have a different scope, so the variables $a, $b etc. aren't available inside your function. Trying to use them inside the function would result in Undefined variable notices (if you enable error reporting, that is).
Right now, you're storing the return value of extract() (which is the total number of variables parsed) into your function. You want the values instead, so change your function like so:
function foo($array) {
extract($array);
echo 'My name is '.$a.', and I am '.$b;
}
Note that I've moved the extract() call inside the function. This way, you wouldn't pollute the global scope with random variables (which may have undesired results and will make your debugging hard for no reason).
Now you can call your function, like so:
foo($my_array);
Output:
My name is Prince, and I am Funky
Demo
It's better to avoid extract() altogether, though. See: What is so wrong with extract()?

You can pass your array in your function as you do with any other variable
$my_array = array("a" => "Prince", "b" => "Funky"); // around 10 more
foo($my_array);
function foo($arrayData)
{
echo 'My name is '.$arrayData['a'].', and I am '.$arrayData['b'];
}

Related

How $row =mysqli_fetch_assoc($result) ,is possible in php

We know we can't store a function in variable
<?php
$k = echo("hello");
?>
or
$k = unset($_SESSION['name']);
They all will give error. because we can't store a function in variable directly, but how we can use.
$row = mysqli_fetch_assoc($result);
I know mysqli_fetch_assoc() function output an array which is stored in variable $row . but how a general rule of php is violated. and we are able to store function in a variable
echo and unset are not really functions. If you check the documentation, you'll see that it says:
Return Values
No value is returned
Since no value is returned, you can't assign them to variables.
mysqli_fetch_assoc() is an ordinary function. And like any other function, you can assign its return value to a variable, or pass it as an argument to another function, or use it in an expression.
You would have a hard time programming in PHP if you couldn't assign function values to variables. You couldn't write things like:
$max = max($var1, $var2);
$current_time = time();
We know we can't store a function in a variable
This is not true, but I'll get back to it later.
You are misunderstanding the syntax below:
$variable = functionName();
This does not mean that the function is stored in a variable. It means that the value returned by the function is stored in the variable.
So there is nothing special about:
$row = mysqli_fetch_assoc($result);
You should also know as I hinted at in the beginning, that we can in fact store a function in a variable:
//store the function in variable $func
$func = function($a, $b){return $a + $b;}
//execute the function stored in variable $func
echo $func(2,8); //prints 10
These types of functions -- functions without names -- care called anonymous functions or closures. See the manual

Array of reference to function in PHP

I would like to check value of integer and choose function depending on this. I could do an if-elseif statement as following:
if($a==0) {function0($a);}
if($a==1) {function1($a);}
etc, but I would rather make an array of function, called maybe functionArray, which could be described as follows:
$functionArray=array( function0($a), function1($a) );
etc, so that we execute function based on $a value, which belongs to $functionArray[$a]. Is that possible? There will be over 20 functions depending on $a value, thats why I want to make it easier and avoid big if-elseif block.
Do not name a variable after its type. $functionArray is rather bad name for a variable, you could at least name it a collection, however, in my example I will name it just functions.
function funcOne($a) {
echo $a+1;
}
function funcTwo($a) {
echo $a+2;
}
$functions = array(1 => 'funcOne', 2 => 'funcTwo');
$a = 2;
$functions[$a]($a);
This might not work below PHP 5.4 and you might need additional assignation e.g. $calledFunction = $functions[$a]; $calledFunction($a). Anyway, it's possible, you just need to add them as strings if you are going to use named functions.
You also can use anonymous functions to achieve that as well
$functions = array(1 => function($a) { echo $a+1; }, 2 => function($a) { echo $a+2;});
$a = 2;
$functions[$a]($a);

PHP: Specify argument variable names when calling a function?

This might seem like an academic or useless topic, but I'm curious.
When developing web pages with PHP, I often need to call functions that take several arguments. I frequently need to look up the spec for the function (on php.net or in my include files, if it's a function I defined) to remind myself what the variables are and what order they're in and what the defaults are, etc. I imagine many of you can relate to this.
A function defined like this:
function do_something_awesome ($people_array, $places_recordset, $num_cycles, $num_frogs,
$url = '?default=yes', $submit_name = 'default_submit_label') {
...
}
when called, might look like this:
$result = do_something_awesome($names, $rsTowns, $c, $f);
My question is this: I'd like to write my code in a way that reminds me of which argument corresponds to each variable, during function calls like this. Is it ever legal to call a function as follows?
$result = do_something_awesome($people_array = $names, $places_recordset = $rsTowns,
$num_cycles = $c, $num_frogs = $f);
If not in PHP, are there other languages where method calls can be made in this way?
To answer your first question:
My question is this: I'd like to write my code in a way that reminds me of which argument corresponds to each variable, during function calls like this.
AFAIK, many PHP coders do it by passing in an associative array as the only argument. However, you'll have to do your own variables checking inside the called function.
$result = do_something_awesome(array(
'people_array' => $names,
'places_recordset' => $rsTowns,
'num_cycles' => $c,
'num_frogs' => $f
));
As for:
Is it ever legal to call a function as follows?
It won't cause any PHP errors, but what you are effectively doing is:
$result = do_something_awesome( expression, expression, expression, expression );
See: PHP Functions arguments
PHP won't know to put $people_array = ... or $num_frogs = ... in their corresponding places when you decide to switch their order around. Furthermore, as DCoder said, these expressions actually take place in the current scope, and will change any pre-existing variables without letting you know.
What about using an object as the only argument:
function my_function($arguments) {
if (!is_object($arguments)) throw new Exception();
$default_values = array('arg1' => 'value1', 'arg2' => 'value2');
foreach ($default_values as $key => $default_value)
if (!isset($arguments->$key)) $arguments->$key = $default_value;
## do the job ##
}
## and then
$my_arguments = new stdClass();
$my_arguments->arg2 = 'some_value';
my_function($my_arguments);
You can try this out:
$bas = 'This is passed to the function.';
$bar = 'This will be modified.';
function foo($bar)
{
echo $bar;
}
foo($bar = $bas);
echo $bar;
The output from this script would be 'This is passed to the function.This is passed to the function.'. So like DCoder said, while you can use them and it's perfectly legal but if you had other variables with the same name as the function arguments, this will overwrite them (in this case the original $bar was overwritten).

create a variable name from a string.. php

Generally I pass an array of parameters to my functions.
function do_something($parameters) {}
To access those parameters I have to use: $parameters['param1']
What I would like to do, is run some sort of logic inside this function on those parameters that converts that array into normal variables. My main reasons is just that sometimes I have to pass a whole load of parameters and having to type $parameters['..'] is a pain.
foreach($parameters as $key=>$paremeter) {
"$key" = $parameter;
}
I thought that might work.. but no cigar!
Use extract():
function do_something($parameters) {
extract($parameters);
// Do stuff; for example, echo one of the parameters
if (isset($param1)) {
echo "param1 = $param1";
}
}
do_something(array('param1' => 'foo'));
Try $$key=$parameter.
Just extract the variables from array using extract:
Import variables into the current
symbol table from an array
extract($parameters);
Now you can access the variables directly eg $var which are keys present in the array.
There is the extract function. This is what you want.
$array = array('a'=>'dog', 'b'=>'cat');
extract($array);
echo $a; //'dog'
echo $b; //'cat'

My PHP Function isn't working

I'm having trouble with the following code. What it should do is echo cats.php followed by example.php but it's not echoing the example.php. Any ideas why this might be happening?
$bookLocations = array(
'example.php',
'cats.php',
'dogs.php',
'fires.php',
'monkeys.php',
'birds.php',
);
echo $bookLocations[1];
function findfile($filenumber)
{
echo $bookLocations["$filenumber"];
}
findfile(0);
Try changing,
echo $bookLocations["$filenumber"];
to:
echo $bookLocations[$filenumber];
Edit* To expand on Thomas's correct answer, instead of using global variables, you could change your method to:
function findfile($filenumber, $bookLocations)
{
echo $bookLocations[$filenumber];
}
i believe you may also need to declare the global variable in your function.
global $bookLocations;
Ok, there are two issues.
Variable Scope
Your function doesn't know the array $bookLocations, you need to pass it to your function like so:
function findfile($filenumber, $bookLocations)
Array key
You don't want to wrap your array key in quotes:
wrong: $bookLocations["$filenumber"];
right: $bookLocations[$filenumber];
The quotes in "$filenumber" turn your key into a string, when the keys to your array are all numbers. You are trying to access $bookLocations["1"] when in fact you want to access $bookLocations[1] -- that is to say, 1 is not the same as "1". Therefore, like others have said, you need to get rid of the quotation marks around the key (and check your variable scope too).
function findfile($filenumber)
{
global $bookLocations;
echo $bookLocations[$filenumber];
}
Good-style developers usually avoid global variables. Instead, pass the array to the function as the parameter:
function findfile($files, $filenum)
{
echo $files[$filenum];
}
$bookLocations is out of scope for your function. If you echo $filenumber you will see that it's in scope because you passed it in by value. However, there is no reference to $bookoLocations.
You should pass in $bookLocations
declaration: function findfile($filenumber, $bookLocations){
call: findfile(1, $bookLocations);
You could also to declare $bookLocations as global, but globals should be avoided if possible.

Categories