Home >Backend Development >PHP Tutorial >Analyze the extract() function in PHP (with code examples)
In the daily use of PHP
, we often need to directly change the data in the PHP
array into separate variables for convenience of use, so as not to need to follow the instructions during use. Only the format of the array can be used to use the value of the array. This article will take you to take a look at the built-in function extract()
in PHP to help us solve this trouble.
First let’s take a look at the syntax of the extrac()
function:
extract (array $arr, int $flags = EXTR_OVERWRITE , string $prefix = "" )
$arr: Associative array (numeric indexed array will No results will be produced unless $flags=EXTR_PREFIX_ALL or EXTR_PREFIX_INVALID is used.)
$flags: Optional, the method of treating illegal/numeric and conflicting key names will be based on the removal of flags $ The flags parameter determines
$prefix: optional, only required when $flags=EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID, EXTR_PREFIX_IF_EXISTS. If the result after appending the prefix is not a legal variable name, it will not be imported into the symbol table. An underscore is automatically added between the prefix and the array key name.
Return value: Returns the number of variables successfully imported into the symbol table.
Code example:
1. There is only one parameter $arr
<?php $arr=array( "name"=>"张三", "age"=>"27", "gender"=>"男", "profession"=>"法外狂徒" ); $extract_num=extract($arr); echo $extract_num."<br>"; echo $name."<br>"; echo $age."<br>"; echo $gender."<br>"; echo $profession."<br>";
输出:4 张三 27 男 法外狂徒
2. Three parameters
<?php $profession="职业张三"; $arr=array( "name"=>"张三", "age"=>"27", "gender"=>"男", "profession"=>"法外狂徒", ); $extract_num= extract($arr, EXTR_PREFIX_SAME, "wddx"); echo $extract_num."<br>"; echo $name."<br>"; echo $age."<br>"; echo $gender."<br>"; echo $profession."<br>"; echo $wddx_profession."<br>";
输出: 4 张三 27 男 职业张三 法外狂徒
We will find that the original variable is not overwritten, because the value of $flag
is EXTR_PREFIX_SAME
, The prefix $prefix
<span label="强调" style="font-size: 16px; font-style: italic; font-weight: bold; line-height: 18px;"> is added when a conflict occurs. Recommendation: </span>《<a href="//m.sbmmt.com/toutiao-415599.html" target="_self" style="white-space: normal;">2021 PHP Interview Questions Summary (Collection)</a>》《<a href="//m.sbmmt.com/course/list/29.html" target="_self" style="white-space: normal;">php video tutorial</a>》
The above is the detailed content of Analyze the extract() function in PHP (with code examples). For more information, please follow other related articles on the PHP Chinese website!