w3resource

PHP Array Exercises : Create a range of specified arrays


59. Create a Range-Like Array from a String

Write a PHP program to create a range like the following array.

Array
(
[20] => 2
[21] => 3
[22] => 4
[23] => 5
[24] => 6
[25] => 7
)

Solution:

PHP Code:

<?php
// Use the array_combine function to create an associative array
// The keys are generated using the range function for values from 20 to 25
// The values are generated using the range function for values from 2 to 7
$result = array_combine(range(20, 25), range(2, 7));

// Print the result using the print_r function
print_r($result);

?>

Sample Output:

Array                                                       
(                                                           
    [20] => 2                                               
    [21] => 3                                               
    [22] => 4                                               
    [23] => 5                                               
    [24] => 6                                               
    [25] => 7                                               
) 

Flowchart:

Flowchart: PHP - Create a range of specified arrays

For more Practice: Solve these Related Problems:

  • Write a PHP script to extract two integers from a string and create an associative array where keys are sequential starting at the first integer and values are incremented accordingly.
  • Write a PHP function to parse a string of space-separated numbers and generate an array where each key equals the number minus a constant and the value equals the number plus one.
  • Write a PHP program to convert a string describing a numeric range into an associative array mapping each number to its successor.
  • Write a PHP script to generate an array from a given string by using a custom formula for keys and values based on a starting number.

Go to:


PREV : Combine Two Arrays (Keys and Values).
NEXT : PHP For Loop Exercises Home.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.