create a variable name from a string.. php - 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'

Related

Is that possible to get the reference to an array from the referent of its element?

I currently have a php function, in which the 1st parameter is a reference to an array and the 2nd parameter is one of its keys,
function fun(&$a, $k) {
......
}
I want to modify the function so that I just need to pass one parameter $a[$k]. Inside the function , $a can be extracted from $a[$k] and then I can call array_search($a[$k], $a) to get $k. Is that possible in PHP?
function fun(&$ak) {
// $ak is from $a[$k]
// a php utility to extract $a from $ak? ...
$k = array_search($ak, $a);
}
Short answer: No, there's no way to "extract" that information, because that information doesn't exist in the scope of your function.
Long answer:
As people have pointed out in the comments, you simply cannot do this. If you have a function like this:
function fun(&$foo) {
...
}
there is no information passed to that function about where $foo came from. It could be a standalone variable, an array element ($bar[1]), an object property ($baz->bingo), or anything else (think SomeClass::$bar->baz[$bingo->boingo]). There's no way to tell.
To verify this, try var_dump($ak); in your function; it won't contain any information about what array or object it's in (or its array index or property name). It's just like any other variable.

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

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'];
}

About changing the passed variable to the function

I have a function which converts a one-indexed 2d array to a 1d array.
Example:
Given array:
array(0 => array("name"=>"Roberts", "email"=>"email#email.com"));
Returned array:
array("name"=>"Roberts", "email"=>"email#email.com");
the function is like this:
function to_1d_array($array)
{
return $array[0];
}
But I want the function to change the passed variable directly returning anything. Should I user referencing or what?
Yes, change to:
function to_1d_array(&$array)
{
$array=$array[0];
}
You should be able to use pass-by-reference, like this:
function to_1d_array(&$array)
{
$array = $array[0];
}
Notice the ampersand (&) just before the $array parameter.
The PHP documentation on this topic has more information if you need it.

Setting PHP multidimensional session variable in function

Say I have a function called set_session_variable that looks like:
function set_session_variable($name, $value) {
// ...write value to the specified path
}
How would I write this function (without using an eval) so that I can do something like:
set_session_variable('foo', 'bar'); // Would set $_SESSION['foo'] = 'bar';
set_session_variable('foo[bar][baz]', 'blah'); // Would set $_SESSION['foo']['bar']['baz'] = 'blah';
I highly suggest, that you won't use
set_session_variable('foo[bar][baz]', 'blah');
but instead
set_session_variable('foo', array('bar'=>array('baz' => 'blah')));
Additionally, you don't need a function call for that at all:
$_SESSION['foo']['bar']['baz'] = 'blah';
You can change the implementation of $_SESSION with the session save handler.
If you're only concerned how you could parse a string like 'foo[bar][baz]', this has been asked before, for example use strings to access (potentially large) multidimensional arrays.
A more relevant question is why you need a function at all. Function calls have a cost, and the function doesn't appear to do useful work.
Example assignments:
$_SESSION['foo'] = 'bar';
$_SESSION['foo']['bar']['baz'] = 'blah';
$foo['bar']['baz'] = 'blah';
$_SESSION['foo'] = $foo;
In direct answer to your question: You could parse the value of $name within set_session_variable() using the PCRE module and a regular expression.
Even simpler and faster would be parsing it with sscanf() provided you are able and willing to impose a convention on the naming of array keys.
A cleaner alternative function:
$array['bar']['baz'] = 'blah';
set_session_variable('foo', $array);
function set_session_variable($key, $val) {
$_SESSION[$key] = $val;
}
One way to solve this is to mimic function overloading, example in this post -> PHP function overloading
Another way is to add one string argument to your function, with your array indices delimited.
For example: set_session_variable('foo', 'bar', 'baz;key');
Which saves the value 'bar' into foo['baz']['key'].
All you have to do is tear the 3rd argument apart (i use ; as delimiter here).

Unset a variable variable

How do you unset a variable variable representing an array element?
function remove($var) {
unset($$var);
}
$x=array('a'=>1,'b'=>2);
remove('$x["a"]');
var_dump(isset($x['a']));
The code above doesn't unset the array element x['a']. I need that same remove() function to work with $_GET['ijk'].
Just use unset() or the (unset) cast.
If you want to use a function to unset, something like this would be better.
function removeMemberByKey(&$array, $key) {
unset($array[$key]);
}
It works!
You can try,
function remove(&$var,$key) {
unset($var[$key]);
}
$x=array('a'=>1,'b'=>2);
remove($x,'a');
var_dump(isset($x['a']));
Variable variables cannot be used with superglobals, so if you need it to work for $_GET as well, you need to look at using a different method.
Source: http://php.net/manual/en/language.variables.variable.php
Try This:
<?php
/* Unset All Declair PHP variable*/
$PHP_Define_Vars = array_keys(get_defined_vars());
foreach($PHP_Define_Vars as $Blast) {
// or may be reset them to empty string# ${"$var"} = "";
unset(${"$Blast"});
}
?>
unset is easier to type then remove
When using it with an array element, the array will still exist
You could rewrite your function to treat the parameter as a reference;
EDIT: updated to use alex's code
function remove(&$array, $key){
unset($array[$key]);
}
remove($x,'a');

Categories