PHP: Use Array Keys As Variables | extract()

Would you like to use an arrays key as a normal variable in PHP? Well, the extract() function is a great way to generate variables from an associative arrays keys. In this article I’ll show you how.


Advertisement

Let’s say you have an array like this:

<?php
$arr = array(
	'name' => 'John',
	'age' => 28
);
?>

So, in order to access the value for the array element with the key ‘name’, you will normally have to use something like this:

<?php
echo $arr['name'];
?>

The extract() function allows you to generate a variable for each array element.

<?php
extract ($arr);
?>

Now you can echo the name like this:

<?php
echo $name;
?>

Or like this:

<?php
echo $age;
?>

🙂

Description

The extract function generates a variable for each key of an associative array. If you use the function, you can pass three arguments, whereby argument two and argument three are optional.

extract ( array &$array [, int $flags = EXTR_OVERWRITE [, string $prefix = NULL ]] ) : int

The first argument is the array, from which the data will be extracted.
The second argument determines the way invalid or numeric keys and collisions are treated.
The third argument is used with the second argument.

You can find more Information about the extract() function, flags and prefix at php.net/manual/en/function.extract.php

The extract() function returns the number of generated variables.

By the way: if you want to generate an array from variables, you can use the compact() function.

So have a lot of fun with this cool function and go on coding cool stuff 😉 .


Advertisement
(Visited 35 times, 1 visits today)

Leave a Comment