Page 2 of 2

Re: Can you extract variable, from string of variables?

Posted: Mon Dec 06, 2010 5:32 pm
by McInfo
simonmlewis wrote:How do you extract that number (13) out of $vars, into one held variable?
McInfo wrote:Instead, if not given a second argument, parse_str() will create variables in the current scope that have the same names as those in the given query string.
That means, if you want individual variables instead of an array, do not give $vars to parse_str().

Code: Select all

parse_str(parse_url($url, PHP_URL_QUERY));
Given the same $url as before, the new function call is equivalent to

Code: Select all

$page = "selector";
$menu = "home";
$id1 = "397";
$id2 = "13";
$id3 = "";
$id4 = "";
$id5 = "";
I don't recommend doing it that way, though, because it is easier to find the values if they are in an array. Also, there could be conflicts with existing variables of the same names. To avoid such conflicts, you could encapsulate that part of the code in a function to limit the variable scope.
simonmlewis wrote:There are potentially five 'id*' in $vars, but how do you get each one
If $vars is an array, you can specify a key to get the associated value.

Code: Select all

$vars['id1']
The key is just a string, so it can come from a variable.

Code: Select all

$key = 'id1';
$vars[$key]
You can even build the key by using concatenation in various ways.

Code: Select all

$key = 'id' . '1';
$vars[$key]

Code: Select all

$n = 1;
$key = 'id' . $n;
$vars[$key]

Code: Select all

$n = '1';
$vars['id'.$n]
Similarly, if $id1 and $id2 are variables, you can dynamically access either one by using a syntax such as these.

Code: Select all

$n = 1;
${'id'.$n} // Same as $id1

Code: Select all

$n = 2;
$key = 'id' . $n;
${$key} // Same as $id2

Code: Select all

$n = '1';
$key = 'id' . $n;
$$key // Same as $id1
simonmlewis wrote:and if one is empty, how does you make the script aware?
The empty() function will test that.

Code: Select all

empty($vars['id1'])

Code: Select all

empty($id1)
Of course, for empty()'s return value to actually be useful, it must be passed somewhere, like to if() or var_dump().