Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • compact() and extract() functions in PHP

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 6.96k
    Comment on it

    PHP provides two functions, extract( ) and compact( ), that convert between arrays and variables.

    Both compact() and extract() are Array functions of PHP

    compact():

    The compact() function is used to create an array from variables and their values.

    OR

    The compact() array function in PHP will create an array from a list of variables.

    Syntax
    compact(variable1, variable2...)
    

    Example of compact() function:

    <?php  
    $subject1 = 'Language';  
    $subject2 = 'Math';  
    $subject3 = 'Geography';  
    $subject_list = array('subject2','subject3');  
    $result = compact('subject1', $subject_list);  
    print_r($result);  
    ?>
    
    output:
    Array ( [subject1] => Language [subject2] => Math [subject3] => Geography )
    

    compact is the opposite of extract() but it is important to understand that it does not completely reverse extract().

    Extract():

    PHP extract() function is used to import variables into the local symbol table from an array.

    PHP extract() function does array to variable transformation. It changes over array keys into variable names and array values into variables values.

    PHP extract() function returns the number of variables extracted on success.

    Syntax
    extract(array,extract_rules,prefix)
    

    Example of extract() function:

    <?php
        $Wales = 'Swansea';
        $capitalcities['England'] = 'London';
        $capitalcities['Scotland'] = 'Edinburgh';
        $capitalcities['Wales'] = 'Cardiff';
        extract($capitalcities);
        print $Wales;
    ?>
    

    The extract( ) function automatically creates local variables from an array.

    The names of the variables correspond to keys in the array, and the values of the variables become the values in the array.

    Another Example of extract() function:

    $person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Betty');
    extract($person);
    echo $name.<br/>;
    echo $age.<br/>;
    echo $wife;
    
    output:
    Fred
    35
    Betty
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: