How to Convert Number to Character Array in PHP ?
Last Updated :
20 Mar, 2024
Given a number, the task is to convert numbers to character arrays in PHP. It is a common operation when you need to manipulate or access individual digits of a number.
This can be particularly useful in situations where you need to perform operations on the digits of a number, such as digital root calculations, digit summing, or validations.
Below are the approaches to convert numbers to character arrays in PHP:
Using str_split() Function
The str_split() function is one of the simplest ways to convert a string into an array of characters. To use it with numbers, you first need to convert the number to a string and then use str_split() to split the string into array of characters.
Example: This example shows the use of the above-explained approach.
PHP
<?php
$number = 12345;
// Convert number to string and
// then to character array
$charArray = str_split((string)$number);
print_r($charArray);
?>
OutputArray
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Using Manual Conversion with Loop
A number can be converted to a character array by iterating over each digit. This method gives you more control over the conversion process. First, we convert the integer into a string and then we use for loop to iterate it.
Example: This example shows the use of the above-explained approach.
PHP
<?php
$number = 12345;
$numberStr = (string)$number;
$charArray = [];
// Loop through each character of the string
for($i = 0; $i < strlen($numberStr); $i++) {
// Add each digit to the array
$charArray[] = $numberStr[$i];
}
print_r($charArray);
?>
OutputArray
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Using preg_split() Function
The preg_split()
function is primarily used for splitting strings based on a regular expression pattern.
' // ':
This
empty regular expression pattern matches between each character in the string, effectively splitting it into individual characters.'
-1
':
Indicates that there is no limit to the number of splits that can be performed.PREG_SPLIT_NO_EMPTY
: This flag tells preg_split()
not to return empty matches. In this case, it ensures that consecutive digits are treated as separate elements in the resulting array.
Example: This example shows the use of the above-explained approach.
PHP
<?php
$number = 12345;
$numberAsString = (string) $number;
// preg_split() splits the string according to the regular expression pattern
$charArray = preg_split('//', $numberAsString, -1, PREG_SPLIT_NO_EMPTY);
print_r($charArray);
?>
OutputArray
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Share your thoughts in the comments
Please Login to comment...