Get Off My Lawn
Get Off My Lawn

Reputation: 36311

Looping through letters not working

I have a function, that loops over excel columns. It was working yesterday, but now I am having issues. My function is returning false according to my var_dump() It isn't even entering the for loop (I have echoed out "here" within that loop and nothing was echoed). Why isn't it working?

$max_col does return the correct maximum column

function get_col(PHPExcel $excel, $search, $row = 5, $col = "A"){
    $max_col = (string)$excel->getActiveSheet()->getHighestColumn(); // returns BH
    for($i = (string)$col; $i <= $max_col; $i++){
        $val    = trim($excel->getActiveSheet()->getCell("{$i}{$row}")->getValue());
        $search = preg_quote($search);
        if(preg_match("/$search/isU", $val)){
            return "$i";
        }
    }
    return false;
}

Here is how I am calling the function:

$col = get_col($excel, $sku, 5, "Q");
var_dump($col);

Upvotes: 0

Views: 62

Answers (1)

Mark Baker
Mark Baker

Reputation: 212412

Using a <= comparison for strings will cause you problems because it's an alphabetic comparison, and alphabetically "C" > "BH" Adjust the initial value of $max_col to be one column beyond the max you want to check, and then use a !== comparison

function get_col(PHPExcel $excel, $search, $row = 5, $col = "A"){
    $max_col = $excel->getActiveSheet()->getHighestColumn(); // returns BH
    $max_col++;
    for($i = $col; $i !== $max_col; $i++){
        $val    = trim($excel->getActiveSheet()->getCell("{$i}{$row}")->getValue());
        $search = preg_quote($search);
        if(preg_match("/$search/isU", $val)){
            return "$i";
        }
    }
    return false;
}

Upvotes: 2

Related Questions