0

How could I do something like this

$ranges = array(
    range(34, 37) => 'Group A',
    range(38, 39) => 'Group B',
    range(40, 41) => 'Group C',
);

foreach($ranges as $range_key => $range_value) {
    echo "K: ".$range_key." V: ".$range_value."\n";
}

I get

Warning: Illegal offset type

2
  • Is there a reason you don't do array('Group A' => range(34, 37)) etc.? Commented Nov 1, 2011 at 20:36
  • yes that gives me a multidimensional array and I was looking to populate just an array Commented Nov 1, 2011 at 20:54

4 Answers 4

4

range() returns an array which cannot be used as an array key. You will need to use each value in the returned array as a key, like this:

foreach ( range(34, 37) as $value ) {
    $ranges[$value] = 'Group A';
}
foreach ( range(38, 39) as $value ) {
    $ranges[$value] = 'Group B';
}
foreach ( range(40, 41) as $value ) {
    $ranges[$value] = 'Group C';
}
Sign up to request clarification or add additional context in comments.

Comments

1
function make_range( $first, $last, $value, &$data_array )
{
    if ( $last < $first ) return;

    for( $index = $last; $index >= $first; --$index )
    $data_array[ $index ] = $value;

    ksort( $data_array, SORT_NUMERIC );
}

Comments

1

maybe this would help

$ranges = array_fill( 34, 37, 'Group A' );
print_r( $ranges );

Comments

0

I think you have yours keys and values backwards

$ranges = array(
    'Group A' => range(34, 37),
    'Group B' => range(38, 39),
    'Group C' => range(40, 41),
);

foreach($ranges as $range_key => $range_value) {
    echo "K: ".$range_key." V: ";
    print_r($range_value)
    echo "\n";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.