phparraysmultidimensional-array

Declare a fixed value to each of an array of key values to populate a new associative array


I have a string and a value. I am exploding the string which returns a few results to a list. I want to add each of those items from the list to an array, with the same value assigned to each string. Here is what I have so far:

$count = 3;
$amount = 2500;
$value = ceil ($amount / $count);
$string = "String1, String2, String3, ";
$strings = explode(", ", $string);

I want to run a foreach that puts $strings and $value into an array together. Any pointers?


Solution

  • You can simply use:

    $combo = array_fill_keys( $strings , $value );
    // var_dump( $combo ); // to check you got it right.
    

    This takes the values in your $strings array and uses them as the keys for the new $combo array, setting the same value for each key.