treyBake
treyBake

Reputation: 6560

Create Alphanumeric Range in PHP

I tried using range() in this way:

echo '<pre>'. print_r(range('A1', 'A4'), 1) .'</pre>';

to create this array:

A1
A2
A3
A4

But it actually returned:

Array
(
    [0] => A
)

Reading the docs confirms this kind of use isn't the intended use.

I could use this code to get my desired result:

$myRange = ['A1', 'A2', 'A3', 'A4'];

But it feels inefficient, with 4, it's not so bad but the task becomes Herculian when it goes into triple digits. Is there something built-in to PHP that handles alphanumeric range generation?

Thanks,

Thanks

Upvotes: 3

Views: 762

Answers (3)

Rameshbabu
Rameshbabu

Reputation: 96

Simply get range(0,4) of number array variable and use Join(",A") function and use split with explode() function as show below

echo "<pre>"; print_r(explode(",","A".Join(",A",range(0, 4))));

Upvotes: 1

dWinder
dWinder

Reputation: 11642

You can do it with array_map and range:

$prefix = "A";
$arr = array_map(function ($e) use ($prefix) { return $prefix . strval($e);}, range(1,4));

Or as a function:

function alphanumericRange($prefix, $start, $end)
{
    return array_map(function ($e) use ($prefix) {return $prefix . strval($e);}, range($start, $end));
}

Upvotes: 6

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

How about this way with array_map()?

<?php
function addA($sValue) {
    return 'A'.$sValue;
}

$range = range(1,10);
$alphabet_range = array_map("addA", $range);
print_r($alphabet_range);
?>

DEMO: https://3v4l.org/kGmTL

Upvotes: 2

Related Questions