Monday, 2 February 2015

How to convert an integer to an array in PHP

Convert an integer to an array in PHP

What would be the most simple way to convert an integer to an array of numbers?
Example:
2468 should result in array(2,4,6,8).
Answers:
You can use str_split and intval:
$number = 2468;

    $array  = array_map('intval', str_split($number));

var_dump($array);
Which will give the following output:
array(4) {
  [0] => int(2)
  [1] => int(4)
  [2] => int(6)
  [3] => int(8)
}

 


How to convert array values from string to int?

 

You can use either, "array_walk" or "array_map." Below is a sample code of how to implement  it:

<?php
// array_walk
function to_integer(&$item) {
$item = intval($item);
}

$a = array('1', '2', '3');
array_walk($a, 'to_integer');
var_dump($a);

// array_map
$a = array('1', '2', '3');
$a = array_map('intval', $a);// intval() is a built-in function
var_dump($a);
?>

 

0 comments:

Post a Comment