A
A
artem782017-01-22 03:29:28
PHP
artem78, 2017-01-22 03:29:28

How to loop through table columns in PHP?

Task: loop through all columns. This code works great as long as it $last_columncontains one character.

$last_column = 'AM';
for ($column = 'A'; $column <= $last_column; $column++) {
  echo "$column ";
}

But if in $last_column2 characters, instead of:
ABC ... XYZ AA AB AC ...AK AL AM

Outputs only:
A

It can be done through the column iterator in PHPExcel, but it's more convenient for me to get the column name in the form of letters.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2017-01-22
@Rsa97

$last_column = 'AM';
$column_number = 0;
do {
    $column_name = (($t = floor($column_number / 26)) == 0 ? '' : chr(ord('A')+$t-1)).
                    chr(ord('A')+floor($column_number % 26));
    echo "{$column_name} ";
    $column_number++;
} while ($column_name != $last_column);

A
Alexey Kucheryavenko, 2018-12-28
@A_G_K

Surely the author is not relevant), but for history, let it be ...

$last_column = 'AM';
for ($column = 'A'; $column != $last_column; $column++) {
    echo "$column ";
}
//или 
$column = 'A';
$last_column = 'AM';
while ($column != $last_column) {
    echo $column.' ';
    $column++;
}

//а в частном случае обычно я использую так
//$columnNamesArr массив с именами столбцов
$column_name = 'A';
foreach ($columnNamesArr as $columnName) {
    $objPHPExcel->getActiveSheet()->SetCellValue($column_name.'1', $columName);
    $objPHPExcel->getActiveSheet()->getColumnDimension($column_name)->setAutoSize(true);
    $column_name++;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question