简体   繁体   中英

Any way to quickly define an array with the variable names as indexes in PHP?

Let's say I've got the following variables:

$var1, $var2, $longrandomstringtomakemypoint

I want to insert them into an array like this:

$array_of_things = array('var1' => $var1, 'var2' => $var2, 'longrandomstringtomakemypoint' => $longrandomstringtomakemypoint);

Typing this makes my code feel messy, as I'm having to type the same thing twice.

Is there a shortcut to define an array, with the variable names as indexes?

$my_array = compact('var1', 'var2', 'anothervar');

http://www.php.net/compact

<?php

    // LETS SAY YOU HAVE YOUR VARS WITH THE FOLLOWING ASSIGNED VALUES
    $var1 == "value1";
    $var2 == "value2";
    $longrandomstringtomakemypoint = "value3";

    $result = compact('var1', 'var2', 'longrandomstringtomakemypoint' );

    print_r($result);

    ?>

The output will be:

Array
(
    [var1] => value1
    [var2] => value2
    [longrandomstringtomakemypoint] => value3
)

[http://us1.php.net/compact][1]

My understanding is that you would want to avoid typing the variable names and values twice .
If this is the case , you can achieve it like this but this is opposite to how you are wanting it .
Even though I am doubtful , I have put it anyway :

/*
 *  Put the variables and values into an array
 */

$arrayOfVariables =
    array(
         'var1' => 'var1Value'
        ,'var2' => 'value2Value'
        ,'longrandomstringtomakemypoint' => 'longrandomstringtomakemypointValue'
    );

/*
 *  Iterate and create variable and assign values
 */

foreach( $arrayOfVariables as $variableName => $variableValue )
{
    /*
     *  Variable variables
     */
    ${$variableName} = $variableValue;
}

/*
 *  Now you can use all those as variables
 */

echo $var1 ,' ' ,$var2 ,' ' ,$longrandomstringtomakemypoint;

@TonyArra mentioned about extract function which could replace the above foreach .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM