1
Array ( [0] => id [1] => 4 )
Array ( [0] => first_name [1] => F_NAME )
Array ( [0] => last_name [1] => L_NAME )
Array ( [0] => email [1] => EMAIL )

Hey,

I'm wondering how I can create a variable named after the type of information stored that stores the actual information. For example, there are 4 pieces of data in the above array. I'd like to have:

$id = 4;
$first_name = 'F_NAME';
$last_name = 'L_NAME';
$email = 'EMAIL';

I know I can use a double $ to create a variable with the name of another variable but don't know how to access the data with this array structure. Any help is appreciated!

Thanks

2 Answers 2

1

I think you're looking for this:

$a = array(
  array('id', '4'), array('first_name', 'F_NAME'), // ...
);

foreach ($a as $b)
{
  $$b[0] = $b[1];
}

But this is a very ugly thing to do, and I'd recommend rethinking the higher strategy a bit.

Sign up to request clarification or add additional context in comments.

1 Comment

See mailo's answer for a better way to store and access this kind of data (associated arrays).
0

You can use PHP extract,but only in case when id=>4 association is in array, not what you have now.

$var_array = array("color" => "blue",
                   "size"  => "medium",
                   "shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");

echo "$color, $size, $shape, $wddx_size\n";

But I think that proper approach would be to modify a little your array and use it like: $data['first_name'], though - interesting question.

1 Comment

That's true, but he could iterate over array to make it 1-D for extract(), anyways I provided a better solution suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.