0

I want to generate an array of strings with a specific range. From 0000000000 to 9999999999.

What have I done is:

$range = range('0000000000', '9999999999', '1111111111');

Above code returns an array of ints:

array(10) {
  [0]=>
  int(0)
  [1]=>
  int(1111111111)
  [2]=>
  int(2222222222)
  [3]=>
  int(3333333333)
  [4]=>
  int(4444444444)
  [5]=>
  int(5555555555)
  [6]=>
  int(6666666666)
  [7]=>
  int(7777777777)
  [8]=>
  int(8888888888)
  [9]=>
  int(9999999999)
}

Is it possible to get from the range function an array of strings numbers or do it differently in a nice way (without loop)?

1 Answer 1

2

Use array_map

<?php
$range = range('0000000000', '9999999999', '1111111111');
var_dump(array_map('strval',$range));

This will return:

array(10) {
  [0]=>
  string(1) "0"
  [1]=>
  string(10) "1111111111"
  [2]=>
  string(10) "2222222222"
  [3]=>
  string(10) "3333333333"
  [4]=>
  string(10) "4444444444"
  [5]=>
  string(10) "5555555555"
  [6]=>
  string(10) "6666666666"
  [7]=>
  string(10) "7777777777"
  [8]=>
  string(10) "8888888888"
  [9]=>
  string(10) "9999999999"
}

Alternatively, for 0 to be returned as 0000000000, (as per @Franz Gleichmann comments)

<?php
$range = range('0000000000', '9999999999', '1111111111');
$rangeElements = array_map(function($range) {
    return str_pad($range, 10, '0', STR_PAD_LEFT); 
}, $range);
var_dump($rangeElements);

or

<?php
$range = range('0000000000', '9999999999', '1111111111');
$rangeElements = array_map(function($range) {
    return sprintf('%010d', $range); 
}, $range);
var_dump($rangeElements);

so output:

array(10) {
  [0]=>
  string(10) "0000000000"
  [1]=>
  string(10) "1111111111"
  [2]=>
  string(10) "2222222222"
  [3]=>
  string(10) "3333333333"
  [4]=>
  string(10) "4444444444"
  [5]=>
  string(10) "5555555555"
  [6]=>
  string(10) "6666666666"
  [7]=>
  string(10) "7777777777"
  [8]=>
  string(10) "8888888888"
  [9]=>
  string(10) "9999999999"
}
Sign up to request clarification or add additional context in comments.

1 Comment

I guess he wants the first item to be "0000000000", so maybe adding a str_pad would be an option?

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.