php compare alphabet position? - php

I have two variables such as:
var1 = "z";
var2 = "A";
how can I check if var1 is after in the alphabet than var2 (in this case it should return true)?

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.

What did you try?... pretty sure this works
<?php
if(strcmp($var1,$var2) > 0) {
return true;
}

If you're comparing a single character, you can use ord(string). Note that uppercase values compare as less than lowercase values, so convert the char to lowercase before doing the comparison.
function earlierInAlphabet($char1, $char2)
{
$char1 = strtolower($char1);
$char2 = strtolower($char2);
if(ord($char1) < ord($char2))
return true;
else
return false;
}
function laterInAlphabet($char1, $char2)
{
$char1 = strtolower($char1);
$char2 = strtolower($char2);
if(ord($char1) > ord($char2))
return true;
else
return false;
}
If you're comparing a string (or even a character) then you can also use strcasecmp(str1, str2):
if(strcasecmp($str1, $str2) > 0)
// str1 is later in the alphabet

return strcmp($var1,$var2) > 0?

You should use http://php.net/manual/en/function.strcmp.php
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
So
return strcmp(var1, var2) > 0 // will return true if var1 is after var2

This solution may be over-the-top for just two variables; but this is for ever if you need to solve if a bunch of variables (2+) would be in the right order...
<?php
$var1='Z';
$var2='a';
$array1 = array();
$array[] = $var1;
$array1[] = $var2;
$array2 = sort($array1);
if($array2 === $array1){
return true;
}else{
return false;
}
?>
Other than that if you only want to do it with two variables this should work just fine.
<?php
return (strcmp($var1,$var2) > 0);
?>

Related

usort and compare function with arguments PHP

I have question
My code works but i dont understand what is $x[1] and $y[1] in function
I tryed $x[0], $x[1], $x[2], $y[0], $y[1], $y[2] and dont get the logical output ? Where i am wrong to understand ? Please if someone can help me ?
<?php
$products = array( array('TIR', 'Tires', 100),
array('OIL', 'Oil', 10),
array ('SPK', 'Spark Plugs', 4));
//print_r ($products); echo '<br />';
function compare($x, $y) {
if ($x[1] == $y[1]) {
return 0;
} else if ($x[1]<$y[1]) {
return -1;
} else {
return 1;
}
}
usort ($products, 'compare');
echo compare('Tires', 'Tires' );
echo compare('Oil', 'Spark Plugs' );
echo compare('Spark Plugs', 'Oil' );
echo compare('Tires', 'Tires');
echo '<br />';
Output is for this code for echo 1, 2, 3, 4:
0
-1
1
0
When you call the compare($x, $y) function, you are passing the strings as the parameters. These string are treated as arrays with 0-based indexing.
So, when echo compare('Tires', 'Tires' ); is executed, these two strings are passed and according to compare function, the character at index 1(indexing starts at 0) i.e. 2nd character is compared.
So, for this ```echo compare('Tires', 'Tires' );```, the compared characters are 'i' and 'i' which are equal and hence 0 is returned.
So, for this echo compare('Oil', 'Spark Plugs' );, the compared characters are 'i' and 'p'. 'i' is less than p and hence -1 is returned. To decide which character is lower than the other, lookup ASCII codes.
And so on for other function calls. Let me know, if you still have any doubt.
This I have explained for just the independent echo compare('Oil', 'Spark Plugs' ); line not for usort function.
UPDATE For the usort function
Let me first explain the way a comparator functions works. Whenever two parameters are passed to the compare function, it returns true or false and this is used to determine whether you need to swap those values or not.
In the earlier case, echo compare('Tirez', 'Tires' );
$x = Tires, and
$y = Tirez
You compare $x[1] and $y[1], particularly the character at index 1. But what if in the case of these strings, you just do $x < &y, the strings are compared automatically character-by-character according to ASCII codes for English alphabets and the result is returned on the first position, the characters do not match.
i.e. if you want to compare if one string is lexicographically smaller than the other string then you can use the below comparator function.
function compare($x, $y) {
if ($x == $y) {
return 0;
} else if ($x < $y) {
return -1;
} else {
return 1;
}
}
The output will be 1, since while comparing character-by-character 'z' > 's'.
So, when a complete array is passed to compare function, the first two elements are passed. Here the array $products is a 2D array (an array of arrays), so the first two arrays are passed
i.e. $x = array('TIR', 'Tires', 100), and
      $y = array('OIL', 'Oil', 10)
So, it depends on your requirement. For example, if you want to sort by index 0 of any array of $products i.e. 'TIR', 'OIL', 'SPK' then change the comparator function to $x[0] and $y[0].
I hope you are able to understand now :).

New to PHP, need to ignore part of a variable in a function

So I'm attempting to concatenate two integers that form a whole serial number to verify if a user has the correct serial code. My second variable will always begin with P, how would I ignore the P from a user input while still having it appear in the concatenated variables in a function like this?
$a = '1800';
$b = P100000000;
if ($a >= "1800" && $b >= "100000000") {
echo "$a-$b is correct";
} else {
echo "I'm sorry, that serial does not match our system.";
}
One way is to use ltrim.
if ($a >= "1800" && ltrim($b, 'P') >= "100000000") { ...
If the P isn't there for some reason, it won't remove anything.
Another way to remove all non-numeric characters from a string and convert it to an integer for comparison would be something like:
intval( filter_var( $b, FILTER_SANITIZE_NUMBER_INT ) )
the filter_var function returns a string, and the intval function returns the integer value from a string.
<?php
$a = 1800; // no quotes here for a number
$b = 'P100000000'; // quotes here please
$real_b = (int)substr($b,1); // cut the first letter, then cast to int
if ($a >= 1800 && $real_b >= 100000000) { // no quotes here for numbers or its a string
echo "$a-$b is correct";
} else {
echo "I'm sorry, that serial does not match our system.";
}
Could also use regex if you have multiple non-digit beginning character;
<?php
$a = '1800';
$b = P100000000;
$b = preg_replace('/^\D/', '', $b);
print("${b}\n");

Check if whole string contains same character

I want to check if a string contains a character repeated zero or more times, for example:
If my string is aaaaaa, bbbb, c or ***** it must return true.
If it contains aaab, cd, or **%*** it must return false.
In other words, if the string has 2 or more unique characters, it must return false.
How to go about this in PHP?
PS: Is there a way to do it without RegEx?
You could split on every character then count the array for unique values.
if(count(array_count_values(str_split('abaaaa'))) == 1) {
echo 'True';
} else {
echo 'false';
}
Demo: https://eval.in/760293
count(array_unique(explode('', string)) == 1) ? true : false;
You can use a regular expression with a back-reference:
if (preg_match('/^(.)\1*$/', $string)) {
echo "Same characters";
}
Or a simple loop:
$same = true;
$firstchar = $string[0];
for ($i = 1; $i < strlen($string); $i++) {
if ($string[$i] != $firstchar) {
$same = false;
break;
}
}
For the fun of it:
<?php
function str2Dec($string) {
$hexstr = unpack('H*', $string);
$hex = array_shift($hexstr);
return hexdec($hex);
}
function isBoring($string) {
return str2Dec($string) % str2Dec(substr($string, 0, 1)) === 0;
}
$string1 = 'tttttt';
$string2 = 'ttattt';
var_dump(isBoring($string1)); // => true
var_dump(isBoring($string2)); // => false
Obviously this works only in small strings because once it gets big enough, the INT will overflow and the mod will not produce the correct value. So, don't use this :) - posting it just to show a different idea from the usual ones.
strlen(str_replace($string[0], '', $string)) ? false : true;
You can check that the number of unique characters is greater than 1. This will perform well even if the input string is empty: (Demo)
$string = 'aaaba';
var_export(
strlen(count_chars($string, 3)) < 2 // false
);
Alternatively, you can trim the string by its first character, but this will generate warnings/notices if the input string has no length. (Demo)
$string = 'aaaba';
var_export(
!strlen(trim($string, $string[0])) // false
);
p.s. Yes, you could use !strlen(trim($string, #$string[0])) to prevent warnings/notices caused by a zero-length string, but I avoid error suppression like the plague because it generally gives code a bad smell.
Regex: ^(.)\1{1,}
^: Starting of string
(.): Match and capture single characted.
\1{1,}: using captured character one or more than once.
For this you can use regex
OR:
PHP code demo
$string="bbbb";
if($length=strlen($string))
{
substr_count($string,$string[0]);
if($length==substr_count($string,$string[0]))
{
echo "Do something";
}
}

comparing two variables returns false result

Why does this always return true:
$s = '334rr';
$i = (int)$s;
if ($i == $s) {
echo true;
} else {
echo false;
}
If I echo $i it gives the value of 334, which is different from $s which is 334rr.
From the manual:
If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.
So: ($i == $s) is the same as ($i == (int)$s) for the values you've given.
Use === to avoid type-juggling.
When compare string with integer using ==, string will try to case into integer.
Try this
$s = '334rr';
$i = intval($s);
if ($i == $s) {
echo true;
} else {
echo false;
}
Comparing strings to an int is not recommended. You should use the === instead which will verify the same data type as well as the same value.
PHP converts the $s string to an integer when comparing to another integer ($i).
It basically does this (well, i don't know what it does internally, but it boils down to this):
if($i == (int) $s)
Which makes the statement true

How do I convert a string to a number in PHP?

I want to convert these types of values, '3', '2.34', '0.234343', etc. to a number. In JavaScript we can use Number(), but is there any similar method available in PHP?
Input Output
'2' 2
'2.34' 2.34
'0.3454545' 0.3454545
You don't typically need to do this, since PHP will coerce the type for you in most circumstances. For situations where you do want to explicitly convert the type, cast it:
$num = "3.14";
$int = (int)$num;
$float = (float)$num;
There are a few ways to do so:
Cast the strings to numeric primitive data types:
$num = (int) "10";
$num = (double) "10.12"; // same as (float) "10.12";
Perform math operations on the strings:
$num = "10" + 1;
$num = floor("10.1");
Use intval() or floatval():
$num = intval("10");
$num = floatval("10.1");
Use settype().
To avoid problems try intval($var). Some examples:
<?php
echo intval(42); // 42
echo intval(4.2); // 4
echo intval('42'); // 42
echo intval('+42'); // 42
echo intval('-42'); // -42
echo intval(042); // 34 (octal as starts with zero)
echo intval('042'); // 42
echo intval(1e10); // 1410065408
echo intval('1e10'); // 1
echo intval(0x1A); // 26 (hex as starts with 0x)
echo intval(42000000); // 42000000
echo intval(420000000000000000000); // 0
echo intval('420000000000000000000'); // 2147483647
echo intval(42, 8); // 42
echo intval('42', 8); // 34
echo intval(array()); // 0
echo intval(array('foo', 'bar')); // 1
?>
In whatever (loosely-typed) language you can always cast a string to a number by adding a zero to it.
However, there is very little sense in this as PHP will do it automatically at the time of using this variable, and it will be cast to a string anyway at the time of output.
Note that you may wish to keep dotted numbers as strings, because after casting to float it may be changed unpredictably, due to float numbers' nature.
Instead of having to choose whether to convert the string to int or float, you can simply add a 0 to it, and PHP will automatically convert the result to a numeric type.
// Being sure the string is actually a number
if (is_numeric($string))
$number = $string + 0;
else // Let the number be 0 if the string is not a number
$number = 0;
Yes, there is a similar method in PHP, but it is so little known that you will rarely hear about it. It is an arithmetic operator called "identity", as described here:
Aritmetic Operators
To convert a numeric string to a number, do as follows:
$a = +$a;
If you want get a float for $value = '0.4', but int for $value = '4', you can write:
$number = ($value == (int) $value) ? (int) $value : (float) $value;
It is little bit dirty, but it works.
You can use:
(int)(your value);
Or you can use:
intval(string)
In PHP you can use intval(string) or floatval(string) functions to convert strings to numbers.
You can always add zero to it!
Input Output
'2' + 0 2 (int)
'2.34' + 0 2.34 (float)
'0.3454545' + 0 0.3454545 (float)
Just a little note to the answers that can be useful and safer in some cases.
You may want to check if the string actually contains a valid numeric value first and only then convert it to a numeric type (for example if you have to manipulate data coming from a db that converts ints to strings). You can use is_numeric() and then floatval():
$a = "whatever"; // any variable
if (is_numeric($a))
var_dump(floatval($a)); // type is float
else
var_dump($a); // any type
Here is the function that achieves what you are looking for. First we check if the value can be understood as a number, if so we turn it into an int and a float. If the int and float are the same (e.g., 5 == 5.0) then we return the int value. If the int and float are not the same (e.g., 5 != 5.3) then we assume you need the precision of the float and return that value. If the value isn't numeric we throw a warning and return null.
function toNumber($val) {
if (is_numeric($val)) {
$int = (int)$val;
$float = (float)$val;
$val = ($int == $float) ? $int : $float;
return $val;
} else {
trigger_error("Cannot cast $val to a number", E_USER_WARNING);
return null;
}
}
If you want the numerical value of a string and you don't want to convert it to float/int because you're not sure, this trick will convert it to the proper type:
function get_numeric($val) {
if (is_numeric($val)) {
return $val + 0;
}
return 0;
}
Example:
<?php
get_numeric('3'); // int(3)
get_numeric('1.2'); // float(1.2)
get_numeric('3.0'); // float(3)
?>
Source: https://www.php.net/manual/en/function.is-numeric.php#107326
I've been reading through answers and didn't see anybody mention the biggest caveat in PHP's number conversion.
The most upvoted answer suggests doing the following:
$str = "3.14"
$intstr = (int)$str // now it's a number equal to 3
That's brilliant. PHP does direct casting. But what if we did the following?
$str = "3.14is_trash"
$intstr = (int)$str
Does PHP consider such conversions valid?
Apparently yes.
PHP reads the string until it finds first non-numerical character for the required type. Meaning that for integers, numerical characters are [0-9]. As a result, it reads 3, since it's in [0-9] character range, it continues reading. Reads . and stops there since it's not in [0-9] range.
Same would happen if you were to cast to float or double. PHP would read 3, then ., then 1, then 4, and would stop at i since it's not valid float numeric character.
As a result, "million" >= 1000000 evaluates to false, but "1000000million" >= 1000000 evaluates to true.
See also:
https://www.php.net/manual/en/language.operators.comparison.php how conversions are done while comparing
https://www.php.net/manual/en/language.types.string.php#language.types.string.conversion how strings are converted to respective numbers
In addition to Boykodev's answer I suggest this:
Input Output
'2' * 1 2 (int)
'2.34' * 1 2.34 (float)
'0.3454545' * 1 0.3454545 (float)
Only multiply the number by 1 so that the string is converted to type number.
//String value
$string = "5.1"
if(is_numeric($string)){
$numeric_string = $string*1;
}
Alright so I just ran into this issue. My problem is that the numbers/strings in question having varying numbers of digits. Some have no decimals, others have several. So for me, using int, float, double, intval, or floatval all gave me different results depending on the number.
So, simple solution... divide the string by 1 server-side. This forces it to a number and retains all digits while trimming unnecessary 0's. It's not pretty, but it works.
"your number string" / 1
Input Output
"17" 17
"84.874" 84.874
".00234" .00234
".123000" .123
"032" 32
Here is a function I wrote to simplify things for myself:
It also returns shorthand versions of boolean, integer, double and real.
function type($mixed, $parseNumeric = false)
{
if ($parseNumeric && is_numeric($mixed)) {
//Set type to relevant numeric format
$mixed += 0;
}
$t = gettype($mixed);
switch($t) {
case 'boolean': return 'bool'; //shorthand
case 'integer': return 'int'; //shorthand
case 'double': case 'real': return 'float'; //equivalent for all intents and purposes
default: return $t;
}
}
Calling type with parseNumeric set to true will convert numeric strings before checking type.
Thus:
type("5", true) will return int
type("3.7", true) will return float
type("500") will return string
Just be careful since this is a kind of false checking method and your actual variable will still be a string. You will need to convert the actual variable to the correct type if needed. I just needed it to check if the database should load an item id or alias, thus not having any unexpected effects since it will be parsed as string at run time anyway.
Edit
If you would like to detect if objects are functions add this case to the switch:
case 'object': return is_callable($mixed)?'function':'object';
$a = "10";
$b = (int)$a;
You can use this to convert a string to an int in PHP.
I've found that in JavaScript a simple way to convert a string to a number is to multiply it by 1. It resolves the concatenation problem, because the "+" symbol has multiple uses in JavaScript, while the "*" symbol is purely for mathematical multiplication.
Based on what I've seen here regarding PHP automatically being willing to interpret a digit-containing string as a number (and the comments about adding, since in PHP the "+" is purely for mathematical addition), this multiply trick works just fine for PHP, also.
I have tested it, and it does work... Although depending on how you acquired the string, you might want to apply the trim() function to it, before multiplying by 1.
Late to the party, but here is another approach:
function cast_to_number($input) {
if(is_float($input) || is_int($input)) {
return $input;
}
if(!is_string($input)) {
return false;
}
if(preg_match('/^-?\d+$/', $input)) {
return intval($input);
}
if(preg_match('/^-?\d+\.\d+$/', $input)) {
return floatval($input);
}
return false;
}
cast_to_number('123.45'); // (float) 123.45
cast_to_number('-123.45'); // (float) -123.45
cast_to_number('123'); // (int) 123
cast_to_number('-123'); // (int) -123
cast_to_number('foo 123 bar'); // false
function convert_to_number($number) {
return is_numeric($number) ? ($number + 0) : FALSE;
}
You can use:
((int) $var) ( but in big number it return 2147483647 :-) )
But the best solution is to use:
if (is_numeric($var))
$var = (isset($var)) ? $var : 0;
else
$var = 0;
Or
if (is_numeric($var))
$var = (trim($var) == '') ? 0 : $var;
else
$var = 0;
Simply you can write like this:
<?php
$data = ["1","2","3","4","5"];
echo json_encode($data, JSON_NUMERIC_CHECK);
?>
There is a way:
$value = json_decode(json_encode($value, JSON_NUMERIC_CHECK|JSON_PRESERVE_ZERO_FRACTION|JSON_UNESCAPED_SLASHES), true);
Using is_* won't work, since the variable is a: string.
Using the combination of json_encode() and then json_decode() it's converted to it's "true" form. If it's a true string then it would output wrong.
$num = "Me";
$int = (int)$num;
$float = (float)$num;
var_dump($num, $int, $float);
Will output: string(2) "Me" int(0) float(0)
Now we are in an era where strict/strong typing has a greater sense of importance in PHP, I use json_decode:
$num = json_decode('123');
var_dump($num); // outputs int(123)
$num = json_decode('123.45');
var_dump($num); // outputs float(123.45)
You can change the data type as follows
$number = "1.234";
echo gettype ($number) . "\n"; //Returns string
settype($number , "float");
echo gettype ($number) . "\n"; //Returns float
For historical reasons "double" is returned in case of a float.
PHP Documentation
If you don't know in advance if you have a float or an integer,
and if the string may contain special characters (like space, €, etc),
and if it may contain more than 1 dot or comma,
you may use this function:
// This function strip spaces and other characters from a string and return a number.
// It works for integer and float.
// It expect decimal delimiter to be either a '.' or ','
// Note: everything after an eventual 2nd decimal delimiter will be removed.
function stringToNumber($string) {
// return 0 if the string contains no number at all or is not a string:
if (!is_string($string) || !preg_match('/\d/', $string)) {
return 0;
}
// Replace all ',' with '.':
$workingString = str_replace(',', '.', $string);
// Keep only number and '.':
$workingString = preg_replace("/[^0-9.]+/", "", $workingString);
// Split the integer part and the decimal part,
// (and eventually a third part if there are more
// than 1 decimal delimiter in the string):
$explodedString = explode('.', $workingString, 3);
if ($explodedString[0] === '') {
// No number was present before the first decimal delimiter,
// so we assume it was meant to be a 0:
$explodedString[0] = '0';
}
if (sizeof($explodedString) === 1) {
// No decimal delimiter was present in the string,
// create a string representing an integer:
$workingString = $explodedString[0];
} else {
// A decimal delimiter was present,
// create a string representing a float:
$workingString = $explodedString[0] . '.' . $explodedString[1];
}
// Create a number from this now non-ambiguous string:
$number = $workingString * 1;
return $number;
}
All suggestions lose the numeric type.
This seems to me a best practice:
function str2num($s){
// Returns a num or FALSE
$return_value = !is_numeric($s) ? false : (intval($s)==floatval($s)) ? intval($s) :floatval($s);
print "\nret=$return_value type=".gettype($return_value)."\n";
}
//Get Only number from string
$string = "123 Hello Zahid";
$res = preg_replace("/[^0-9]/", "", $string);
echo $res."<br>";
//Result 123

Categories