-4

I have list of numbers

1112
1113
1114
1115
1116-1117
1118-1119
1120
1121-1122

Need to show these numbers like following

1x112
1x113
1x114
1x115
1x120

And these number explode with - and show like

1x116
1x117
1x118
1x119
1x121
1x122
HP371
  • 860
  • 11
  • 24
Akaash K
  • 11
  • 6

4 Answers4

0

Cast your numbers to string, and then you can manipulate them :

$a = 1112;
$a = (string) $a;
var_dump(substr($a, 0, 1) . 'x' . substr($a, 1)); /* "1x112" */
Altherius
  • 754
  • 7
  • 23
0

Try the below code. It's working for you.

<?php
    $numStr = '1112 1113 1114 1115 1116-1117 1118-1119 1120 1121-1122';
    $numStr = explode(' ',str_replace('-',' ',$numStr));

    foreach($numStr as $key => $num) {
        $numStr[$key] = substr($num, 0, 1) . 'x' . substr($num, 1);
    }

    echo $numStr = implode(' ',$numStr);
?>

OUTPUT

1x112 1x113 1x114 1x115 1x116 1x117 1x118 1x119 1x120 1x121 1x122 
Mukesh Singh Thakur
  • 1,335
  • 2
  • 10
  • 23
0

Try with convert into array like this.

<?php 
$a = array();
$a[] = 1112;
$a[] = 1113;
$a[] = 1114;
$a[] = 1115;
$a[] = '1116-1117';
$a[] = '1118-1119';
$a[] = 1120;
$a[] = '1121-1122';

$output = array();
foreach($a as $key=>$value){
    if (strpos($value, '-') !== false) {
        $sub_a = explode('-',$value);
        foreach($sub_a as $sub_key=>$sub_value){
            $output[$key][$sub_key] = substr($sub_value, 0, 1).'x'.substr($sub_value, 1);       
        }
    }else{
        $output[$key] = substr($value, 0, 1).'x'.substr($value, 1);
    }
}
print_r($output);

Output

Array
(
    [0] => 1x112
    [1] => 1x113
    [2] => 1x114
    [3] => 1x115
    [4] => Array
        (
            [0] => 1x116
            [1] => 1x117
        )

    [5] => Array
        (
            [0] => 1x118
            [1] => 1x119
        )

    [6] => 1x120
    [7] => Array
        (
            [0] => 1x121
            [1] => 1x122
        )

)
HP371
  • 860
  • 11
  • 24
0

Split on any non-digit, and then substitute part of the string:

<?php
$list = '1112 1113 1114 1115 1116-1117 1118-1119 1120 1121-1122';
foreach(preg_split('/[^0-9]/', $list) as $number)
    echo substr_replace($number, 'x', 1, 0), "\n";

Output:

1x112
1x113
1x114
1x115
1x116
1x117
1x118
1x119
1x120
1x121
1x122
Progrock
  • 7,373
  • 1
  • 19
  • 25