Pedro Silva
Pedro Silva

Reputation: 23

Compare incremental strings

so this is kinda hard to form a question about my issue so just picture what i'm going to explain,

image you have a list of multiple strings that contain characters from A to Z after Z it goes to AA, AB, AC etc etc...

I want to get the highest on the list for that i'm trying to do something like this:

$max_letter = "A";
while($row = mysqli_fetch_assoc($recordset)) {
    if($row["new_letter"] > $max_letter) {
        $max_letter = $row["new_letter"];
    }
}

the problem with this is that when $row["new_letter"] is equal to "AA" and $max_letter is equal to "Z" it doesn't update $max_letter to "AA" because it thinks "Z" is higher than "AA"

but if i do something like this:

$str = "Z";
echo ++$str;

my output will be

AA

example of my problem:

$str = "Z";
echo ++$str;

echo "<br><br>";

if("AA" > "Z") {
    echo "higher";
}elseif("AA" == "Z") {
    echo "equal";   
}elseif("AA" < "Z") {
    echo "lower";
}

Upvotes: 2

Views: 128

Answers (3)

NappingRabbit
NappingRabbit

Reputation: 1918

this would likely work:

$max_letter = "A";
while($row = mysqli_fetch_assoc($recordset)) {
    if(cvrt($row["new_letter"]) > cvrt($max_letter)) {
        $max_letter = $row["new_letter"];
    }
}

function cvrt(incStr){
    $ret = "";
    foreach(str_split(incStr) as $v){
        $ret .= ord($v);
    }
    return $ret;
}

not pretty but I think it will work for any length of string.

what you are doing here is concatenating the numerical values of the letters in the string and returning them to be compared as a number.

Upvotes: 0

Dale
Dale

Reputation: 10469

Build an array of all your letters.. this problem becomes trivial then :)

$maxLetters = ['a', 'b', 'c', 'z', 'aa'];

natsort($maxLetters);

echo array_pop($maxLetters) . ' is the highest letter';

I'll try to fit this to your needs

$maxLetters = [];
while($row = mysqli_fetch_assoc($recordset)) {
    $maxLetters[] = $row['new_letter'];
}
natsort($maxLetters);
$highestLetter = array_pop($maxLetters);
echo $highestLetter;

Upvotes: 0

Eakethet
Eakethet

Reputation: 682

I would try to write some function to convert char val to int val

<?php

//echo ord('A') - 64;
// so base is -64
// 26 chars
// read from beggining

$value = 0;
// 27 in charval
$charVal = 'AA';

$len = strlen($charVal);
$i = 0;

while ($i < $len) {
    if ($value != 0) {
        $value *= 26;
    }
    $value += ord($charVal[$i]) - 64;
    $i++;
}

echo $value;

So you make it function and call if (charToInt('AA') > charToInt('Z') {...

Upvotes: 1

Related Questions