Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment letters like number by certain value in php

Tags:

php

phpexcel

In php if I writ

$c='A';
$c++;
it increments to 'B' but if I want to increment it with 2 ,3 or more , eg: $c+2 or $c+3 ,to get the alternate alphabets

 for ($column = 'B'; $column < $highestColumn; $column++) {   
 $cell = $worksheet->getCell($column.$row);
 $cell2=$worksheet->getCell($column+1.$row);
 }

but the $column+1 dont work

how to do that ?

like image 788
Swanand Keskar Avatar asked Jan 05 '23 10:01

Swanand Keskar


1 Answers

Incrementing letters will only work with the ++ incrementor operator, not with + addition.

If you want to continue using an incrementor, you can use a loop:

$column = 'AH';
$step = 7; // number of columns to step by
for($ = 0; $i < $step; $i++) {
    $column++;
}

However, PHP's character incrementor won't work backwards, so you couldn't use a negative step value


If you want to use addition rather than a loop, then you need to convert that column to a numeric value, do the addition, then convert back

$column = 'AH';
$step = 7; // number of columns to step by
$columnNumber = PHPExcel_Cell::columnIndexFromString($column) + $step;
$column = PHPExcel_Cell::stringFromColumnIndex($columnNumber - 1);

Which has the added benefit of allowing you to use negative step values

like image 58
Mark Baker Avatar answered Jan 13 '23 09:01

Mark Baker