Home >>PHP Array Functions >PHP extract() Function

PHP extract() Function

Use of extract() function in PHP

PHP extract() function is used to convert an array in to variables. It converts the array keys into variable names and the array values into variable value. It accepts three parameters out of which only one is mandatory and other two are optional. It returns the number of variables extracted from the array on success.

Syntax:

 extract($array, $extract_rules, $prefix);

Parameter Values

Parameter Description
array This is a required parameter. This parameter defines the array to use.
extract_rules This is an optional parameter. This parameter defines how invalid and colliding names are treated.
prefix This is an optional parameter. This parameter defines the prefix.

Here is an example of extract() function in PHP:

<html>
<body>
<?php
$array = array("a" => "111","b" => "222", "c" => "333");
extract($array);
echo "$a = $a <br>$b = $b <br>$c = $c";
?>
</body>
</html>
Output:
$a = 111  
$b = 222  
$c = 333  

Example 2:

<html>
<body>
<?php
$a = "000";
$array = array("a" => "111","b" => "222", "c" => "333");
extract($array, EXTR_PREFIX_SAME, "dup");
echo "$a = $a <br>$b = $b <br>$c = $c <br>$dup_a = $dup_a";
?>
</body>
</html>
Output:
$a = 000  
$b = 222  
$c = 333  
$dup_a = 111  	

Example 3

<?php
extract($_POST);		
if(isset($save))
{
echo "<center>";
echo "Your Name : ".$fn."<br>";
echo "Your Last Name : ".$ln."<br>";
echo "Your Email : ".$eid."<br>";
echo "Your Course : ".$course."<br>";
echo "</center>";
}		
?>
<html>
	
<head>
		
<title>use of extract() in Php</title>
			

	
</head>
	
<body bgcolor="sky color">
		
<form method="post" >
			
<table border="1" align="center" bgcolor="green">
				
<tr>
					
<td>Enter your first Name</td>
					
<td><input type="text" name="fn"/></td>
				
</tr>
				
<tr>
					
<td>Enter your Last name</td>
					
<td><input type="text" name="ln"/></td>
				
</tr>

<tr>
					
<td>Enter your Email</td>
					
<td><input type="email" name="eid"/></td>
				
</tr>

<tr>
					
<td>Select Your Course</td>
					
<td>
<select name="course">
	<option>Php</option>
	<option>java</option>
	<option>Perl</option>
</select>
</td>
				
</tr>

				
<tr align="center">			
					
<td colspan="2" >
					
<input type="submit" value="Display Output" name="save"/></td>
				
</tr>
					
</table>
		
</form>
	
</body>

</html>

No Sidebar ads