arrays - How to create a function to return variables in php

465

I want to create a function by which i can get variables..

for example

$var = array("site_name" => "site_value", "site_des" => "site_value2");

foreach ($var as $key => $val){
$$key = $val;
}
echo $site_name; // print site_value

this code works but when i insert it in a function like

function get_var(){
$var = array("site_name" => "site_value", "site_des" => "site_value2");
foreach ($var as $key => $val){
$$key = $val;
}
}

and i want to get this vars in a function link

function get_other(){
get_var();
return 'hi '.$site_name; // hi site_value
}

Actual i want global variable in function but i have a large no of global variables and i have to write each global variable in function each time when i make a function.

so if there is any other good method to do this please let me know..

482

Answer

Solution:

You can use extract()

$var = array("site_name" => "site_value", "site_des" => "site_value2");
extract($var);

echo $site_name; // outputs: site_value

Be sure to check the flags section in the documentation on how to deal with overwriting local variables or prefixing the keys in your array.

A little example. Since your$var could come for anywhere and basically change our global or local vars, thus making your code unsafe, you can for instance make sure to only extract known varsEXTR_IF_EXISTS or you can choose to prefix all the vars:

extract($var, EXTR_PREFIX_ALL, "ext");
echo $ext_site_name;
667

Answer

Solution:

If i'm reading You correctly, you want to use $GLOBALS superglobal array to set new global variable like this:

function test()
{
  $GLOBALS [ "test" ] = "value";
}
test();
print ( "My variable: " . $test . "\n" );

Check above code at codepad. It outputsMy variable: value.

Your code then could looks like:

function get_var(){
  $var = array("site_name" => "site_value", "site_des" => "site_value2");
  foreach ($var as $key => $val){
    $GLOBALS[$key] = $val;
  }
}
function get_other(){
  get_var();
  return 'hi '.$GLOBALS["site_name"]; // hi site_value
}

EDIT: I've created codepad for Your code also, check it here.

People are also looking for solutions to the problem: php - How to add an action button for a specific row in gridview YII2 Advanced Template?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.