If INT equals 3,5,8,10,13,15 (etc) - php

I want to have an if statement in PHP to calculate if an INT equals only certain numbers. The pattern would go like: 3, 5, 8, 10, 13, 15, 18, 20 etc. It adds 3, then 2, repeating. The pattern is consistent with the last digit (3,5,8,0), but I don't want to include the first 0.
I could do it this way, but it could go on forever...
if($int == 3 || $int == 5 || $int == 8 || $int == 10 ....)
{
//do stuff
}
This way also does multiples of 3...
if ($int % 3 == 0)
{
//do stuff
}
But doesn't do the pattern I want. What's the right way of doing this?

You can do it like this.
Get the remainder of the division by 10 and then check for 0, 3, 5 or 8.
if ($int > 0) {
$int = $int % 10;
if ($int == 0 || $int == 3 || $int == 5 || $int == 8)
{
//do stuff
}
}

function check($t) {
$mod = $t % 10;
if ($mod == 0 || $mod == 3 || $mod == 5 || $mod == 8)
echo $t;
}
$arr = array(3, 6, 8, 10, 20, 13, 15, 19);
array_map('check', $arr);

Related

Is there a known way to validate an Estonian business ID?

I have to validate an Estonian business ID (not a citizen ID). The ID is 9 numbers, but I think there might be a system of assigning them. For example, here is the Finnish validation with the last number as the checksum
if (preg_match('/^\d{7}-\d{1}$/', $user_input)) {
list($num, $control) = preg_split('[-]', $user_input);
// Add leading zeros if number is < 7
$num = str_pad($num, 7, 0, STR_PAD_LEFT);
$controlSum = 0;
$controlSum += (int)substr($num, 0, 1)*7;
$controlSum += (int)substr($num, 1, 1)*9;
$controlSum += (int)substr($num, 2, 1)*10;
$controlSum += (int)substr($num, 3, 1)*5;
$controlSum += (int)substr($num, 4, 1)*8;
$controlSum += (int)substr($num, 5, 1)*4;
$controlSum += (int)substr($num, 6, 1)*2;
$controlSum = $controlSum%11;
if ($controlSum == 0) {
return ($controlSum == $control) ? true : false;
} elseif ($controlSum >= 2 && $controlSum <= 10 ) {
return ((11 - $controlSum) == $control) ? true : false;
}
}
Usually there is a checksum for all of these types of IDs, so it's not just a matter of running a regex on it, but I can't find anything relating to Estonian businesses.
Any links to known libraries, examples would be appreciated. I'm working in PHP, but these could be in any language.
Thanks.
You can include a SOAP-Call from the European Commission https://ec.europa.eu/taxation_customs/vies/vatRequest.html
It should work like this (not 100% tested):
$vatId = "{{the vat id }}";
$client = new SoapClient("http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl");
if ($client) {
$cc = substr($vatId, 0, 2);
$vn = substr($vatId, 2);
$params = array('countryCode' => $cc, 'vatNumber' => $vn);
$result = $client->checkVat($params);
if ($result->valid == true) {
echo "VAT-ID ok";
}
} else {
die("connection failed");
}
I found this library, which answers my question
https://github.com/arthurdejong/python-stdnum/blob/master/stdnum/ee/registrikood.py
from stdnum.exceptions import *
from stdnum.util import clean, isdigits
def calc_check_digit(number):
"""Calculate the check digit."""
check = sum(((i % 9) + 1) * int(n)
for i, n in enumerate(number[:-1])) % 11
if check == 10:
check = sum((((i + 2) % 9) + 1) * int(n)
for i, n in enumerate(number[:-1])) % 11
return str(check % 10)
def compact(number):
"""Convert the number to the minimal representation. This strips the
number of any valid separators and removes surrounding whitespace."""
return clean(number, ' ').strip()
def validate(number):
"""Check if the number provided is valid. This checks the length and
check digit."""
number = compact(number)
if not isdigits(number):
raise InvalidFormat()
if len(number) != 8:
raise InvalidLength()
if number[0] not in '1789':
raise InvalidComponent()
if number[-1] != calc_check_digit(number):
raise InvalidChecksum()
return number
def is_valid(number):
"""Check if the number provided is valid. This checks the length and
check digit."""
try:
return bool(validate(number))
except ValidationError:
return False

PHP Variable declaration not working in Laravel 5.4

I have the following code in a Laravel 5.4 Blade view:
#php($strVal = $character->Strength)
#php($strMod = 0)
<?php
if ($strVal == 10 || 11) {
$strMod = 0;
} elseif ($strVal == 12 || 13) {
$strMod = 1;
} elseif ($strVal == 14) {
$strMod = 2;
} else {
$strMod = 2;
}
?>
It takes data from a MySQL table.
$strVal is an int from the table. The code creates a var called $strMod and goes through a number of if/elseif statements to see what it will be equal to.
It's shown on a webpage as follows:
<div class="huge charMod">+{{$strMod}}</div>
My issue is that it displays as "+0" no matter what strVar equals. strVar is working fine, I can pull it from the DB and display it via {{ $strVal }} but strMod refuses to take a value other than 0.
$strVal == 10 || 11 will always return true
Because that's not how comparisons work in PHP. The == operator has a higher precedence than || operator, so it will be performed first.
It means that $strVal == 10 || 11 gets turned into false || 11 .. which is true.
Instead of that code, I would recommend:
$map = [
10 => 0,
11 => 0,
12 => 1,
13 => 1,
// you dont actually need 14, because default value is aready 2
];
$result = 2;
if (array_key_exists($strVal, $map)) {
$result = $map[$strVal];
}
$strVal = $result;
Or, if you are using PHP 7.0+ it all can actually be written as:
$map = [10 => 0, 11 => 0, 12 => 1, 13 => 1];
$strVal = $map[$strVal] ?? 2;
You need to change your if checks to
if ($strVal == 10 || $strVal == 11) {
$strMod = 0;
} elseif ($strVal == 12 || $strVal == 13) {
$strMod = 1;
} elseif ($strVal == 14) {
$strMod = 2;
} else {
$strMod = 2;
}
if ($strVal == 10 || 11) will always return true. If you want to check two values you need to specify that by using the variable == value again as in the example above.

How to format a number as 2.5K if a thousand in PHP? Like Facebook [duplicate]

This question already has answers here:
Shorten long numbers to K/M/B?
(14 answers)
Closed 8 years ago.
I need to show a page views value in the format of 1K of equal to one thousand, or 1.1K, 1.2K, 1.9K etc, if its not an even thousands, otherwise if under a thousand, display normal 500, 100, 250 etc, using PHP to format the number?
I'm using:--
function count_number($n) {
// first strip any formatting;
$n = (0+str_replace(",","",$n));
// is this a number?
if(!is_numeric($n)) return false;
// now filter it;
if($n>1000000000000) return round(($n/1000000000000),1).'T';
else if($n>1000000000) return round(($n/1000000000),1).'G';
else if($n>1000000) return round(($n/1000000),1).'M';
else if($n>1000) return round(($n/1000),1).'K';
return number_format($n);
}
BUT it does not work correctly...
If my page visted 2454 times, it shows 2.5k and if 2990, it shows 3k...
How o fix that problem??
I want to SHOW Like --> if page visited 2454 -> how to display 2.4k and if 2990 -> 2.9k, if 3000 -> 3k etc
Plz help me...
Thanks # MonkeyZeus
Now itz DONE...
function kilo_mega_giga($n) {
if($n >= 1000 && $n < 1000000)
{
if($n%1000 === 0)
{
$formatted = ($n/1000);
}
else
{
$formatted = substr($n, 0, -3).'.'.substr($n, -3, 1);
if(substr($formatted, -1, 1) === '0')
{
$formatted = substr($formatted, 0, -2);
}
}
$formatted.= 'k';
} else
if($n >= 1000000 && $n < 1000000000)
{
if($n%1000000 === 0)
{
$formatted = ($n/1000000);
}
else
{
$formatted = substr($n, 0, -6).'.'.substr($n, -6, 1);
if(substr($formatted, -1, 1) === '0')
{
$formatted = substr($formatted, 0, -2);
}
}
$formatted.= 'M';
} else
if($n >= 1000000000 && $n < 1000000000000)
{
if($n%1000000000 === 0)
{
$formatted = ($n/1000000000);
}
else
{
$formatted = substr($n, 0, -9).'.'.substr($n, -9, 1);
if(substr($formatted, -1, 1) === '0')
{
$formatted = substr($formatted, 0, -2);
}
}
$formatted.= 'G';
} else
if($n >= 0 && $n < 1000)
{
$formatted= $n;
}
return $formatted;
}
You can use this to calculate thousands. You can use this formula to figure out the formula for millions as well.
$n = 2000;
$formatted = '';
if($n >= 1000 && $n < 1000000)
{
if($n%1000 === 0)
{
$formatted = ($n/1000);
}
else
{
$formatted = substr($n, 0, -3).'.'.substr($n, -3, -2);
if(substr($formatted, -1, 1) === '0')
{
$formatted = substr($formatted, 0, -2);
}
}
$formatted.= 'k';
}
echo $formatted;
Also, please use curly braces, ALWAYS. Future you will thank present you.
What about number greater than 10000
function facebookFormattter($digit) {
if ($digit >= 1000000000) {
return round($digit/ 1000000000, 1). 'G';
}
if ($digit >= 1000000) {
return round($digit/ 1000000, 1).'M';
}
if ($digit >= 1000) {
return round($digit/ 1000, 1). 'K';
}
return $digit;
}

Fix for convert fraction short PHP snippet, issue with calculation converting a fraction to more readable format

Here is the problem, when it encounters fractions like: 300/10 instead of giving a result of "30"
the following code gives me: 1/0
$tokens = explode('/', $value);
while ($tokens[0] % 10 == 0) {
$tokens[0] = $tokens[0] / 10;
$tokens[1] = $tokens[1] / 10;
}
if ($tokens[1] == 1) {
return $tokens[0].' s';
} else {
return '1/'.floor(1/($tokens[0]/$tokens[1])).' s';
// return $tokens[0].'/'.$tokens[1].' s';
}
thanks
You should change the line while($tokens[0] % 10 === 0 && $tokens[1] % 10 === 0) { to while($tokens[0] % 10 === 0 && $tokens[1] % 10 === 0) {.
And the line return '1/'.floor(1/($tokens[0]/$tokens[1])).' s'; is not reliable.
If you want to reduce fractions, try this function:
function reduceFraction($fraction) {
sscanf($fraction, '%d/%d %s', $numerator, $denominator, $junk);
// TODO: validation
if( $denominator === null ) {
return (string)$numerator;
}
if( $numerator === $denominator ) {
return 1;
}
$max = max(array($numerator, $denominator));
for($i = 1; $i < $max; ++$i) {
if( $denominator % $i === 0 && $numerator % $i === 0) {
$common = $i;
}
}
if( $denominator === $common ) {
return (string)($numerator / $common);
}
return ($numerator / $common) . '/' . ($denominator / $common);
}
You could use it like this:
reduceFraction('300/10') . ' s';
It's also possible to generalize more the function for chained fractions (eg: '300/100/10'). I can send an implementation of it if you wish.
tell me why the "while ($tokens[0] % 10 == 0 && $tokens[1] % 10 ==0)"
would be better to use than just "while ($tokens[0] % 100 == 0)" since
both methods seem to work ok
If you try to use the string "3000/10" as an argument for each implementation, the one with while ($tokens[0] % 10 == 0 && $tokens[1] % 10 ==0) will return 300 s, and the other with while ($tokens[0] % 100 == 0) will return 1/0 s.
If you use the while ($tokens[0] % 100 == 0) method, the loop iterations are:
$tokens[0] = 3000 / 10 = 300;
$tokens[1] = 10 / 10 = 10;
$tokens[0] = 30 / 10 = 30;
$tokens[1] = 10 / 1 = .1;
Stopped because 30 % 100 != 0.
Since the $token[1] is not 1, it does not return "30 s".
1/30 is less than zero (0.0333...), thus floor(1/30) = 0. That's why it returns "1/0 s".
If you use the while ($tokens[0] % 10 == 0 && $tokens[1] % 10 == 0) method, the loop iterations are:
$tokens[0] = 3000 / 10 = 300;
$tokens[1] = 10 / 10 = 1;
Stopped because 1 % 10 != 0.
Since the $token[1] is not 1, it returns "30 s".
It is better because it will work with more inputs.
But I recommend you to use the "reduceFraction" function that I implemented.
It uses the maximum common denominator technique to reduce functions.
echo reduceFraction('3000/10'); outputs "300".
echo reduceFraction('300/10'); outputs "30".
echo reduceFraction('30/10'); outputs "3".
echo reduceFraction('3/10'); outputs "3/10".
echo reduceFraction('3/3'); outputs "1".
echo reduceFraction('222/444'); outputs "1/2".
echo reduceFraction('444/222'); outputs "2".

PHP: How can I determine if a variable has a value that is between two distinct constant values?

How can I determine using PHP code that, for example, I have a variable that has a value
between 1 and 10, or
between 20 and 40?
if (($value > 1 && $value < 10) || ($value > 20 && $value < 40))
Do you mean like:
$val1 = rand( 1, 10 ); // gives one integer between 1 and 10
$val2 = rand( 20, 40 ) ; // gives one integer between 20 and 40
or perhaps:
$range = range( 1, 10 ); // gives array( 1, 2, ..., 10 );
$range2 = range( 20, 40 ); // gives array( 20, 21, ..., 40 );
or maybe:
$truth1 = $val >= 1 && $val <= 10; // true if 1 <= x <= 10
$truth2 = $val >= 20 && $val <= 40; // true if 20 <= x <= 40
suppose you wanted:
$in_range = ( $val > 1 && $val < 10 ) || ( $val > 20 && $val < 40 ); // true if 1 < x < 10 OR 20 < x < 40
You can do this:
if(in_array($value, range(1, 10)) || in_array($value, range(20, 40))) {
# enter code here
}
if (($value >= 1 && $value <= 10) || ($value >= 20 && $value <= 40)) {
// A value between 1 to 10, or 20 to 40.
}
Sorry for the late answer, but this function allow you to do that.
function int_between($value, $start, $end) {
return in_array($value, range($start, $end));
}
// Example
$value1 = 20;
$value2 = 40;
echo int_between(20, $value1, $value2) ? "true" : "false";
Guessing from the tag 'operand' you want to check a value?
$myValue = 5;
$minValue = 1;
$maxValue = 10;
if ($myValue >= $minValue && $myValue <= $maxValue) {
//do something
}
If you just want to check the value is in Range, use this:
MIN_VALUE = 1;
MAX_VALUE = 100;
$customValue = min(MAX_VALUE,max(MIN_VALUE,$customValue)));
Try This
if (($val >= 1 && $val <= 10) || ($val >= 20 && $val <= 40))
This will return the value between 1 to 10 & 20 to 40.

Categories