PHP extract() - PHP Array To Variable Example


Share:
Published By: Admin, Published On: Apr 23, 2021, Category: PHP

Hi Guys,

In this blog, I will show you how to extract() function is used to import variables from an array into the current symbol table. It takes an associative array array and treats keys as variable names and values as variable values. For each key/value pair it will engender a variable in the current symbol table, subject to extract_type and prefix parameters.

Syntax:
extract($array, $extract_type, $prefix)

Parameters

  1. array(Required) - It specifies an array
  2. extract_type(Optional) - The extract() function checks for invalid variable names and collisions with existing variable names. This parameter designates how invalid and colliding denominations are treated.Possible values −
    • EXTR_OVERWRITE - Default. On collision, the existing variable is overwritten
    • EXTR_SKIP - On collision, the existing variable is not overwritten
    • EXTR_PREFIX_SAME - On collision, the variable name will be given a prefix
    • EXTR_PREFIX_ALL - All variable names will be given a prefix
    • EXTR_PREFIX_INVALID - Only invalid or numeric variable names will be given a prefix
    • EXTR_IF_EXISTS - Only overwrite existing variables in the current symbol table, otherwise do nothing
    • EXTR_PREFIX_IF_EXISTS - Only add prefix to variables if the same variable exists in the current symbol table
    • EXTR_REFS - Extracts variables as references. The imported variables are still referencing the values of the array parameter
  3. prefix(Optional) - If EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS are utilized in the extract_rules parameter, a designated prefix is required.

    This parameter specifies the prefix. The prefix is automatically separated from the array key by an underscore character.

Return

It returns the number of variables successfully imported into the symbol table.

Here i will give you full example for extract() function using php So let's see the bellow all example:

Example
<?php

$array = array("a" => "111","b" => "222", "c" => "333","m" => "MyWebTuts");
extract($array);
echo "$a , $b , $c , $m";

?>
Output
111 , 222 , 333 , MyWebTuts

Example : 2 with EXTR_PREFIX_SAME parameter.

<?php

$a = "000";
$array = array("a" => "111","b" => "222", "c" => "333","m" => "MyWebTuts");
extract($array,EXTR_PREFIX_SAME,"dup");
echo "$a , $b , $c , $m ,$dup_a";

?>
Output
000 , 222 , 333 , MyWebTuts , 111
It will help you..
Share: