Jaxkr
Jaxkr

Reputation: 1283

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?

Upvotes: 1

Views: 162

Answers (3)

Tony Arra
Tony Arra

Reputation: 11119

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

http://www.php.net/compact

Upvotes: 6

Uours
Uours

Reputation: 2492

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 .

Upvotes: 0

slash28cu
slash28cu

Reputation: 1634

<?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]

Upvotes: 0

Related Questions