Fueling Your Coding Mojo

Buckle up, fellow PHP enthusiast! We're loading up the rocket fuel for your coding adventures...

Popular Searches:

Split 4 digit number into 2 variables in PHP

Hey everyone,

I'm currently working on a PHP project where I need to split a 4-digit number into two separate variables. But I'm not sure how to do it. Can someone please help me out with this?

To provide you with some context, I have a 4-digit number stored in a variable. Let's say the number is 1234. Now, I want to split this number into two separate variables, where one variable will hold the first two digits (12 in this case), and the other variable will hold the last two digits (34 in this case).

I have already tried a few methods but none of them seem to work. Can anyone please suggest a reliable and efficient way to achieve this? Your help would be greatly appreciated.

Thanks in advance!

All Replies


Hey folks,

I came across a similar requirement recently and found a different approach to split a 4-digit number into two variables in PHP. Here's how I tackled it:

$number = 1234;
$numberArray = array_map('intval', str_split($number)); // Convert the number to an array of integers

$firstTwoDigits = $numberArray[0] * 10 + $numberArray[1]; // Calculate the first two digits
$lastTwoDigits = $numberArray[2] * 10 + $numberArray[3]; // Calculate the last two digits

In this approach, I first converted the 4-digit number to an array of integers using `str_split()` and `array_map()` functions. Each digit of the number is now a separate element in the array.

After that, I computed the first two digits by multiplying the first element in the array by 10 and adding the second element. Similarly, I obtained the last two digits by multiplying the third element by 10 and adding the fourth element.

By using this method, the value of the `$firstTwoDigits` variable should be `12`, and the `$lastTwoDigits` variable should be `34`.

Give it a try and let me know if you face any issues or have any questions!

Best regards,


Hey there,

One way to split a 4-digit number into two variables in PHP is by using string manipulation functions. Here's a method that worked for me in a similar situation:

$number = 1234;
$numberString = strval($number); // Convert the number to a string

$firstTwoDigits = substr($numberString, 0, 2); // Extract the first two digits
$lastTwoDigits = substr($numberString, 2); // Extract the last two digits

In the above code, I first convert the 4-digit number to a string using `strval()` function. Then, I use the `substr()` function to extract the desired portions of the string based on their positions.

After executing this code, the `$firstTwoDigits` variable will hold the value `12`, and the `$lastTwoDigits` variable will hold `34`.

I hope this solution works for you. Let me know if you have any further questions or need any additional assistance!


New to LearnPHP.org Community?

Join the community