Extract one number from another number in PHP [duplicate] - php

This question already has answers here:
What is the best way to validate a credit card in PHP?
(8 answers)
Closed 7 years ago.
so tonight i was trying to create a function that will check if a credit card is valid or not.
However i'm stuck here.
In my calcul, i get number such as 10, 56, 30... number with 2 numbers.
(I mean, 1 is a number with 1 number just like 2, 3, 4 ,5 6, 7 , 8 ,9.. number with two numbers would be 10 ans higher.)
What I need to do is :
Get the first number and add it to a new variable, and do the same thing with another variable.
Example:
I have this number -> 23
I need to :
$var1 = 2;
$var2 = 3;
I wanted to use the function subtr, but it looks like it doesn't works with numbers ..
Thanks for reading !!

I hope you get something from this. Casting the number into a string first and then split the number using substr() after that cast the splitted value to integer again:
$num = 23;
$str_num = (string)$num;
$var1 = (int)substr($str_num, 0, 1);
$var2 = (int)substr($str_num, 1, 1);
Or using a pure numbers:
$num = 23;
$var2 = $num % 10;
$var1 = ($num - $var2) / 10;

Credit card numbers can be validated using an algorithm called the Luhn Algorithm.
If you need this in a project, don't reinvent the wheel. Check out this project on github.

Here's a way to do this using purely numbers (without ever casting to strings). This'll also work on any length of numbers assigning it to $var1, $var2, ... , $varn for n length number.
$num = 23;
$count = 1;
while ($num > 0) {
$var = "var".$count++;
$$var = $num % 10;
$num = intval($num / 10);
}

a numeric solution
$num = 23;
$var1 = floor($num / 10);
$var2 = $num % 10;
echo "$var1 $var2";

Related

converting number from higher to lower [duplicate]

This question already has answers here:
PHP: How to sort the characters in a string?
(5 answers)
Closed 2 years ago.
we are trying to reorder the number
for example
5695479 to 9976554
48932 to 98432
means all bigger numbers then smaller number.
i was searching for some inbuilt function in php, we found sort function can do with array.
$numbers=array(4,6,2,22,11);
sort($numbers);
function my_sort($a,$b)
{
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}
$a=array(4,2,8,6);
usort($a,"my_sort");
i have searched lot but i could not found any inbuilt functions.
There is no specific in-built function for this. However, you can use more than 1 inbuilt function to accomplish your task.
You can convert the integer to string usingstrval.
Now, split the string by each digit to get an array of integers.
Apply rsort() to sort them in descending order.
Implode() them back to get the number you desire.
Snippet:
<?php
$str = strval(5695479);
$nums = str_split($str);
rsort($nums);
echo implode("",$nums);
Another alterantive is to use counting sort for digits. Since digits will always be between 0-9, collect their count and loop from 9 to 0 and get the new number. This method would be faster than the first method if you have the number in string format with huge lengths.
Snippet:
<?php
$num = 48932; // if number is in string format, loop char by char using for loop
$count = [];
while($num > 0){
if(!isset($count[$num % 10])) $count[$num % 10] = 0;
$count[$num % 10]++;
$num = intval($num / 10);
}
$new_num = 0;
for($i = 9; $i >=0; --$i){
if(!isset($count[$i])) continue;
while($count[$i]-- > 0) $new_num = $new_num * 10 + $i; // you would rather concatenate here incase of string.
}
echo $new_num;

Reduce a number to single digit by adding its digits recursively

How to reduce a number to single digit by adding its individual digits recursively :
Example 1 : $n = 99999 >> 45 >> 9
Example 2 : $n = 444444 >> 24 >> 6
Example 3 : $n = 8888888888888885 >> 125 >> 8;
then get equal to at last we want to get single digit.
You can use array_sum and str_split into a while loop until the final value of $n has the length equal to 1.
$n = 4444;
while (strlen($n) > 1) {
$n = array_sum(str_split($n));
}
var_dump($n);
Without array_sum and str_split you can use something like:
$n = '4444';
while (strlen($n) > 1) {
$s = 0;
for ($i = 0; $i < strlen($n); $i++) {
$s += $n[$i];
}
$n = (string) $s;
}
var_dump($n);
You can calculate this in a much more simple and elegant way, let me try to explain. For example if you have the number 53, you can divide it by 9 and it’s remainder will be it’s reduced number. Don’t ask me how I figured this out, I was just tinkering with numbers. So what you can do is use modulus, (53 % 9 = 8!) (517 % 9 = 4!). Perfect right? Almost, if the number is a multiple of 9 like 45 for example if you “modulus” it by 9 you will receive it’s remaineder which is 0 and we would expect 9 because 45 reduced to a single digit is 9. So you can just make a quick and easy else if statement checking for an output of 0, and if it’s 0 just return 9. Done! Whatever number you out in from 1 to infinty it will reduce it perfectly. Hope this helps :)

doing maths with php array based on excel function

I am new to PHP and stackoverflow and try to figure things out for myself before asking but I am having a little trouble doing some maths on an array I have pulled from a database with PHP.
So far I have an array of numbers called $array['sn']
I have created a function in excel that does the maths and works well in excel but I cant figure out a way to do it in PHP.
the excel function is =QUOTIENT(E32,65536)&QUOTIENT(E32-F34*65536,256)&(G33-G35*256)
E32 being the value I start with i.e $sn
F34 being the answer to the first quotient
G35 being the answer to the second quotient
G33 being E32-F34*65536
I want to take a number e.g. 3675177 divide it by 65536 but without the remainder which is 56, then multiply 56 by 65536 which equals 3670016, then find the difference between 3670016 and 3675177 which is 5161. Then divide 5161 by 256 with no remainder which is 20 then multiply 20 by 256 and subtract 5161 which is 41.
The end result from 3675177 should be 562041. I want to do this calculation on every number in the $array['sn'], any help would be appreciated.
The calculation and formatting of the output would be like this:
$n = 3675177;
$const = 65536;
$const2 = 256;
$a = intval($n / $const); // intval returns only the integer part of a number
$x = $n % $const; // $n % $const means "the remainder of $n / $const"
$b = intval($x / $const2);
$c = $x % $const2;
// Two options to handle values of $c < 10:
// if ($c < 10) $c = "0$c";
// $c = str_pad($c, 2, "0", STR_PAD_LEFT);
echo "$a$b$c";
I would recommend using array_map to apply the calculation to your array of values.
There are php arithmetic operations you can use.
I would do something like this:
$initialNumber = //the initial number, wherever you get it from
$entireDivision = ceil($initialNumber/65536)-1;
$remainder = $initialNumber%65536;
$remainderMultiplied = $remainder * 56;
$difference = $initialNumber - $remainderMultiplied;
$differenceDivided = ceil($difference/256)-1;
$differenceMultipliedAndSubstracted = ($differenceDivided * 256) - $difference;
Maybe I used too many variables, this is to be a bit more easy to understand for you. Maybe I did some operation wrong, check it out too. But this is the idea of mathematic operations in php. Maybe you should put this inside a php function with parameters, so your code gets cleaner if you use multiple times.
EDIT: You should put this code inside a function, then run a foreach loop in your array running this function taking as parameter the value of the array position.
$results = array();
foreach ($array['sn'] as $key => $a) {
$b = intval($a / 65536);
$c = ($a - $b * 65536);
$d = intval($c / 256);
$e = $c - $d * 256;
$results[$key] = $b . $d . $e;
}
var_dump($results);

PHP - Get length of digits in a number

I would like to ask how I can get the length of digits in an Integer. For example:
$num = 245354;
$numlength = mb_strlen($num);
$numlength should be 6 in this example. Somehow I can't manage it to work?
Thanks
EDIT: The example code above --^ and its respective method mb_strlen(); works just fine.
Maybe:
$num = 245354;
$numlength = strlen((string)$num);
Accepted answer won't work with the big numbers. The better way to calculate the length of any number is to invoke floor(log10($num) + 1) with a check for 0.
$num = 12357;
echo $num !== 0 ? floor(log10($num) + 1) : 1; // prints 5
It has multiple advantages. It's faster, you don't do the casting of types, it works on big numbers, it works with different number systems like bin, hex, oct.
The equation does the logarithm with base 10 then makes the floor of it and adds 1.
This solution can work independently on the base, so if you want to calculate the length of binary or hex just change the base of the logarithm.
Working fiddle
The accepted solution presents a problem when evaluating negative numbers.
It works with a positive number:
$num = 245354;
$numlength = strlen((string)$num);
// Result: 6
But with a negative number, the (-) is added to the count:
$num = -245354;
$numlength = strlen((string)$num);
// Result: 7
Quick workaround:
$num = -245354;
$numlength = strlen((string)abs($num));
// Result: 6
More elegant way :)
ceil(log10($num));
You could also use some basic math!
$digits = (int)(log($num,10)+1)
<?php
$num = 123;
$num2 = 1234;
$num3 = 12345;
function digits($num){
return (int) (log($num, 10) + 1);
}
echo "\n $num: " . digits($num); // 123: 3
echo "\n $num2:" . digits($num2); // 1234: 4
echo "\n $num3:" . digits($num3); // 12345: 5
echo "\n";
Another way to find out the length of a number in digits would be to divide the integer part of the number to 10 until it becomes 0.
Example:
2021/10 = 202.1
202/10 = 20.2
20/10 = 2
2/10 = 0.2
Code:
function numberGetLength($number) {
$count = 0;
while (intval($number) > 0) {
$number = intval($number) / 10;
$count += 1;
}
return $count
}
Just using some version of (int)(log($num,10)+1) fails for 10, 100, 1000, etc. It counts the number 10 as 1 digit, 100 as two digits, etc. It also fails with 0 or any negative number.
If you must use math (and the number is non-negative), use:
$numlength = (int)(log($num+1, 10)+1);
Or for a math solution that counts the digits in positive OR negative numbers:
$numlength = ($num>=0) ? (int)(log($num+1, 10)+1) : (int)(log(1-$num, 10)+1);
But the strlen solution is just about as fast in PHP.
In PHP types are loosely set and guessed, if you want to see something as a string if it is an integer, float, and (i have not tried this) bool then #Gorjunav is the most correct answer.
Reset the variable as a string
$stringNum = (string) $num;
Then you can go anything string related you want with it! And vice-versa for changing a string to an int
$number = (int) $stringNum;
and so on...
count only integer value
`<?php
$n1 =12345;
$n2 =123454.55;
$n3 =12345564.557;
echo "The Number you Type: ".$n1."<br>";
$count = 0;
while ($n1 != 0)
{
$n1 = $n1 / 10;
$n1 = intval($n1);
++$count;
}
echo "The Digit in a Number: ".$count;
}
?>`
echo strlen((string) abs($num)); // using **abs** it'll work with negative integers as well
Tested in PHP 4.4.9 - 8.0.0
$array = array(-1, 0, -0, 1, 4, 9, 10, -10, 20, -20, 100, -100);
foreach( $array as $key => $num ){
echo $key."\t{$num}\t=>\t".($num !== 0 ? floor(log10(abs($num)) + 1) : 1)."\n";
}
/* Output:
0 -1 => 1
1 0 => 1
2 0 => 1
3 1 => 1
4 4 => 1
5 9 => 1
6 10 => 2
7 -10 => 2
8 20 => 2
9 -20 => 2
10 100 => 3
11 -100 => 3
*/
The following function work for either integers or floats (works with PHP7+):
function digitsCount($number): int
{
$number = abs($number);
$numberParts = explode(".", $number);
return
strlen($numberParts[0]) +
(strlen($numberParts[1] ?? 0));
}

perform round function without using round() in php [duplicate]

This question already has answers here:
Print numeric values to two decimal places
(6 answers)
Closed 11 months ago.
without use of round() function perfrom the round() in php
$a = "123.45785";
$v = round($a);
output: 123.46;
it had done by round function but i want to get output without use of round and number_format() function.
Here's a way of doing it with arithmetics:
function my_round($num, $places = 2) {
// Multiply to "move" decimals to the integer part
// (Save one extra digit for rounding)
$num *= pow(10, $places + 1);
// Truncate to remove decimal part
$num = (int) $num;
// Do rounding based on the last digit
$lastDigit = $num % 10;
if ($lastDigit >= 5)
$num += 10;
// Remove last digit
$num = (int) ($num/10);
// "Move" decimals in place, and you're done
$num /= pow(10, $places);
return $num;
}
You have sprintf.
$a = "123.45785";
echo sprintf("%01.2f", $a); // output: 123.46

Categories