Variable Position in Comparision in PHP

In PHP, is there a short way to compare a variable to multiple values?

in_array() is what I use

if (in_array($variable, array('one','two','three'))) {

Does variables' order matter when doing == and === comparisons?

It prevents typos which cause very hard to debug bugs. That's in case you accidentally write = instead of ==:

if ($var == null)  # This is true in case $var actually is null
if ($var = null) # This will always be true, it will assign $var the value null

Instead, switching them is safer:

if (null == $var)   # True if $var is null
if (null = $var) # This will raise compiler (or parser) error, and will stop execution.

Stopping execution on a specific line with this problem will make it very easy to debug. The other way around is quite harder, since you may find yourself entering if conditions, and losing variable's values, and you won't find it easily.

PHP: comparison when counting with incremented character variables

Try this:

// From https://stackoverflow.com/a/3580935/3088508
function getLetterIndexInAlphabet ($letter) {
return ord($letter) - 96;
}

function convertStringToNumber ($inStr) {
$letters = array_reverse(str_split($inStr));
$outNum = 0;
for ($i = count($letters) - 1; $i >= 0; $i--) {
$outNum += getLetterIndexInAlphabet($letters[$i]) * (pow(26, $i));
}
return $outNum;
}

function AisLessThanB ($a, $b) {
$aInt = convertStringToNumber($a);
$bInt = convertStringToNumber($b);
return ($aInt < $bInt);
}

convertStringToNumber is the most complicated function in here, so let's have a look at how it works on a few values:

  • 'c' evaluates to 2 which is calculated by:

    1. 'c' = 3 (index in alphabet)
  • 'ba' evaluates to 53 which is calculated by:

    1. 'b' = 52 = (2 (index in alphabet) x (26 (base value) ^ 1 (column number))).
    2. 'a' = 1 (index in alphabet)
  • 'bca' evaluates to 1431 which is calculated by:

    1. 'b' = 1352 = (2 (index in alphabet) x (26 (base value) ^ 2 (column number))).
    2. 'c' = 78 = (3 (index in alphabet) x (26 (base value) ^ 1 (column number))).
    3. 'a' = 1 (index in alphabet)
  • 'bdca' evaluates to 37935 which is calculated by:

    1. 'b' = 35152 = (2 (index in alphabet) x (26 (base value) ^ 3 (column number))).
    2. 'd' = 2704 = (4 (index in alphabet) x (26 (base value) ^ 2 (column number))).
    3. 'c' = 78 = (3 (index in alphabet) x (26 (base value) ^ 1 (column number))).
    4. 'a' = 1 (index in alphabet)

Here's some test cases:

echo "   a < z    = " . ((AisLessThanB(   'a',    'z')) ? 'true' : 'false') . "\n";
echo " z < aa = " . ((AisLessThanB( 'z', 'aa')) ? 'true' : 'false') . "\n";
echo " aa < az = " . ((AisLessThanB( 'aa', 'az')) ? 'true' : 'false') . "\n";
echo " az < zz = " . ((AisLessThanB( 'az', 'zz')) ? 'true' : 'false') . "\n";
echo " zz < aaa = " . ((AisLessThanB( 'zz', 'aaa')) ? 'true' : 'false') . "\n";
echo " aaa < zzz = " . ((AisLessThanB( 'aaa', 'zzz')) ? 'true' : 'false') . "\n";
echo " zzz < aaaa = " . ((AisLessThanB( 'zzz', 'aaaa')) ? 'true' : 'false') . "\n";
echo "\n===================\n\n";
echo " z < a = " . ((AisLessThanB( 'z', 'a')) ? 'true' : 'false') . "\n";
echo " aa < z = " . ((AisLessThanB( 'aa', 'z')) ? 'true' : 'false') . "\n";
echo " az < aa = " . ((AisLessThanB( 'az', 'aa')) ? 'true' : 'false') . "\n";
echo " zz < az = " . ((AisLessThanB( 'zz', 'az')) ? 'true' : 'false') . "\n";
echo " aaa < zz = " . ((AisLessThanB( 'aaa', 'zz')) ? 'true' : 'false') . "\n";
echo " zzz < aaa = " . ((AisLessThanB( 'zzz', 'aaa')) ? 'true' : 'false') . "\n";
echo "aaaa < zzz = " . ((AisLessThanB('aaaa', 'zzz')) ? 'true' : 'false') . "\n";

And they output:

   a < z    = true
z < aa = true
aa < az = true
az < zz = true
zz < aaa = true
aaa < zzz = true
zzz < aaaa = true

===================

z < a = false
aa < z = false
az < aa = false
zz < az = false
aaa < zz = false
zzz < aaa = false
aaaa < zzz = false

eval.in demo

Thanks for asking such an interesting question!

PHP compare two string in random position

$string1 = "1122";
$string1 = str_split($string1);
sort($string1);

$string2 = "1212";
$string2 = str_split($string2);
sort($string2);

if ($string1 == $string2) {
echo "true";
} else {
echo "false";
}

Here is an example that returns true

php compare alphabet position?

I think everyone who has answered agrees that strcmp() is the right answer, but every answer provided so far will give you incorrect results. Example:

echo strcmp( "Z", "a" );

Result: -1

echo strcmp( "z", "A" );

Result: 1

strcmp() is comparing the binary (ord) position of each character, not the position in the alphabet, as you desire. If you want the correct results (and I assume that you do), you need to convert your strings to the same case before making the comparison. For example:

if( strcmp( strtolower( $str1 ), strtolower( $str2 ) ) < 0 )
{
echo "String 1 comes before string 2";
}

Edit: you can also use strcasecmp(), but I tend to avoid that because it exhibits behavior that I've not taken the time to understand on multi-byte strings. If you always use an all-Latin character set, it's probably fine.

Compare variables PHP

$myVar = "hello";
if ($myVar == "hello") {
//do code
}

$myVar = $_GET['param'];
if (isset($myVar)) {
//IF THE VARIABLE IS SET do code
}

if (!isset($myVar)) {
//IF THE VARIABLE IS NOT SET do code
}

For your reference, something that stomped me for days when first starting PHP:

$_GET["var1"] // these are set from the header location so www.site.com/?var1=something
$_POST["var1"] //these are sent by forms from other pages to the php page

Comparing two text variables not working

I see you are declaring $wpdb there. Are you on Wordpress? If so, I found this SO question that has the same problem with you.

What makes the comparation doesn't work, because there's a whitespace or newline characters on one of two variables (see the accepted answer on that post).

Here is the solution, by trimming both strings:

if (trim($ctitle) === trim($odgovor)) ...

Checking on which position is a variable in javascript array

In Javascript you can use Array.prototype.indexOf() for the search of an item in an array. The result is the index starting with 0. If not found, the -1 is returned.

var champions = {    "Aatrox": ["Blood Well", "Dark Flight", "No Q2", "Blood Thirst", "Blood Price", "Blades of Torment", "No E2", "Massacre"],    "Ahri": ["Essence Theft", "Orb of Deception", "Fox-Fire", "Charm", "Spirit Rush"],    "Akali": ["Twin Disciplines", "Mark of the Assassin", "Twilight Shroud", "Crescent Slash", "Shadow Dance"],    "Alistar": ["Trample", "Pulverize", "Headbutt", "Triumphant Roar", "Unbreakable Will"],    "Amumu": ["Cursed Touch", "Bandage Toss", "Despair", "Tantrum", "Curse of the Sad Mummy"]};
function getPos(o,n, s) { return n in o && o[n].indexOf(s);}
document.write(getPos(champions, 'Akali', 'Twin Disciplines') + '<br>');document.write(getPos(champions, 'Akali', 'Mark of the Assassin') + '<br>');


Related Topics



Leave a reply



Submit