Extract and Compact functions in PHP

by Manigandan 2011-06-08 14:10:01

extract :
Extract function import the variable from an array to the current symbol table.
ie. if you have an associative array like $a = array(user_name => midhun devasia, email_id => mymail@mydomain.com), and wanted to use this as variable name, we usually try this method $user_name = $a['user_name']; instead of that we will get all variable into our current symbol table by using extract function.
1 $a = array('user_name' => 'midhun devasia', 'email_id' => 'myemail@mydoamin.com');
2
3 extract($a);
4 echo "Hello ", $user_name, "Your email id is ", $email_id;

The first param is the array, and second param is optional , there you can pass to overwrite the variable values, add prefix etc options. see the PHP Manuel for more info.

compact:
Create array containing variables and their values.
If you want to pass some variable values into an array as its key and values.
1 $user_name = "Midhun Devasia";
2 $email_id = "myemail@domain.com";
3
4 $result = compact("user_name", "email_id");
5
6 /*
7 echo $result['user_name'] is Midhun Devasia
8 */

Tagged in:

1015
like
0
dislike
0
mail
flag

You must LOGIN to add comments