2

I have a function like this:

$conf = array ('test_value' => 1, 'test_value2' => 2);
function GetValueArray($array, $value)
{
     return $array[$value];
}

Im using this function to receive a value from an array. My problem is that i cannot use this function like this:

GetValueArray('conf', 'test_value');

How could i convert 'conf' to the real array named conf to receive my 'test_value'?

Andrei Vlad
  • 215
  • 2
  • 10

1 Answers1

3

Because functions have their own scope, be sure to 'globalize' the variable that you're looking into.

But as Rizier123 said, you can use brackets around a variable to dynamically get/set variables.

<?php

$conf = array ('test_value' => 1, 'test_value2' => 2);

function GetValueArray($array, $value)
{
  global ${$array};
  return ${$array}[$value];
}

echo GetValueArray('conf', 'test_value'); // echos '1'
echo GetValueArray('conf', 'test_value2'); // echos '2'


?>
ChrisJohns.me
  • 174
  • 2
  • 6