H. Ferrence
H. Ferrence

Reputation: 8116

How to initialize a multi-dimensional array in PHP presetting the keys

I have a constant defined as:

define('CONFIG_CODES', 'v1,v2,v3');

I want to initialize a multi-dimensional array using the config codes defined in my constant as the array keys. I have tried array_fill_keys() and a variety of other methods and I cannot get the array to initialize. The reason I want to initialize is to avoid Undefined index: v2 and Undefined offset: 0 in my PHP script results.

Here is what I want the initialization to look like:

Array
(
    [v1] => Array
        (
            [0] => 
            [1] => 
        )

    [v2] => Array
        (
            [0] => 
            [1] => 
        )

    [v3] => Array
        (
            [0] => 
            [1] => 
        )

)

My Attempt:

$serviceTimes = array_fill_keys( array( CONFIG_CODES ), '' );

Upvotes: 0

Views: 1510

Answers (2)

Ice76
Ice76

Reputation: 1130

This could be something like what you are looking for?

define( 'CONFIG_ARRAY', 'v1, v2, v3' );
define( 'VALUES', 2 );

function makeArray()
{
    $array = array();
    $versions = explode( ',', CONFIG_ARRAY );
    foreach ( $versions as $version )
    {
        $array[$version] = array();
        for( $i = 0; $i < VALUES; $i++ )
        {
            $array[$version][$i] = '';
        }
    }
    return $array;
}

This would be a generator function, but you can remove the code from the function and use it to make your array.

Upvotes: 1

whitwhoa
whitwhoa

Reputation: 2489

Create an empty $initialized array, then loop through the exploded result of your constant value, using the exploded values as associative keys:

define('CONFIG_CODES', 'v1,v2,v3');
$initialized = array();
foreach(explode(',', CONFIG_CODES) as $val){
    $initialized[$val] = array(
        'val1',
        'val2'
    );
}

Upvotes: 2

Related Questions