Reputation: 5207
Is it possible to convert array values into one single integer. For example, I have array with numbers
$array = array(7,4,7,2);
Is it possible to get integer value 7472 from this array?
Upvotes: 1
Views: 3250
Reputation: 3663
Use implode
, along with (int)
to convert the string result to an integer:
$a = [7,4,7,2];
$res = (int) implode('', $a);
P.S. Since PHP 5.4 you can also use the short array syntax, which replaces array() with [].
Upvotes: 1
Reputation: 6298
function digitsToInt($array) {
$nn = 0;
foreach ( $array as $digit) {
$nn = $nn * 10 + intval($digit);
}
return $nn;
}
var_dump( digitsToInt(array(7,4,7,2)) ); # int(7472)
Upvotes: 0
Reputation: 22532
Simple use implode
as
$array = array(7,4,7,2);
echo (int)implode("",$array);// 7472
Upvotes: 5
Reputation: 8101
Use implode
function as it create a string out of array and try this :
echo implode("",$array);
Upvotes: 2
Reputation: 1703
Use implode, which creates a string from an array. http://php.net/manual/en/function.implode.php
echo implode($array);
Upvotes: 2