harunB10
harunB10

Reputation: 5207

How to create integer out of array?

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

Answers (5)

D.Dimitrioglo
D.Dimitrioglo

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

napuzba
napuzba

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

Saty
Saty

Reputation: 22532

Simple use implode as

$array = array(7,4,7,2);
echo (int)implode("",$array);// 7472

Upvotes: 5

Dhara Parmar
Dhara Parmar

Reputation: 8101

Use implode function as it create a string out of array and try this :

echo implode("",$array);

Upvotes: 2

Geoff Atkins
Geoff Atkins

Reputation: 1703

Use implode, which creates a string from an array. http://php.net/manual/en/function.implode.php

echo implode($array);

Upvotes: 2

Related Questions