Jump to content

range() - mixing letters with numbers?


deansatch

Recommended Posts

Can I somehow mix letters with numbers to create an array with range()?

 

e.g. I want my array for postcode ranges such as array('AB1','AB2', 'AB3', 'AB4', 'AB5', 'Ab6', 'AB7', 'AB8', 'IV5', 'IV6', 'IV7', 'IV8', 'IV9', 'IV10');

 

I know I can do range(1,8); but was wondering if there was something along the lines of range("AB1", "AB8");

Link to comment
https://forums.phpfreaks.com/topic/246096-range-mixing-letters-with-numbers/
Share on other sites

You could do it, i suppose.  The first thing that sprung in my mind was a load of nested loops.  Which would confuse the hell out of me.

 

I agree with Thorpe.  For the sake of errors: if you're wanting postcodes, then get a database CSV and drop that into the database.  they typically come with long&lat codes making it easier to get distances etc.

Would be simple enough to loop through and build a range with a prefix:

 

function prefix_range($prefix, $from, $to)
{
    if (!is_numeric($from) || !is_numeric($to) || $from > $to) {
        return false;
    }

    $range = array();

    for ($i = $from; $i <= $to; $i++) {
        array_push($range, $prefix . $i);
    }

    return $range;
}

 

Example usage:

 

$ab_range = prefix_range('AB', 1, ;

/*Array
(
    [0] => AB1
    [1] => AB2
    [2] => AB3
    [3] => AB4
    [4] => AB5
    [5] => AB6
    [6] => AB7
    [7] => AB8
)*/

 

Edit

 

Not sure how this will help with real postcodes though?

Thanks all. I eventually did it like so...

 

 

function mixArrayKeyValue(&$value,$key){$value=$value.$key;}
$arrayAB = array_fill(17, 4,'AB');
array_walk($arrayAB, 'mixArrayKeyValue');

$arrayAB2 = array_fill(26, 4,'AB');
array_walk($arrayAB2, 'mixArrayKeyValue');

$mergedArray = array_merge($arrayAB, $arrayAB2);
//etc....

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.