I need to split a string in two so I can do a SELECT query in my DB. For example, I have the number '0801'. I need to split that number into '08' and '01'. How do I manage to do that?
4 Answers
This is easy to do using the substr() function, which lets you pull out parts of a string. Given your comment that you always have a four-digit number and want it split into two two-digit numbers, you want this:
$input = "0801";
$left = substr($input, 0, 2);
$right = substr($input, 2);
echo "Left is $left and right is $right\n";
2 Comments
picaluga
Wow the other guys just showed me this fucntion but you really went balls deep explaining it. Well done now I trully understand. Thank you a lot. Both of you.
TwoStraws
You're welcome! As the answer helped you, please take the time to mark it as correct so others can benefit too. Google brings a lot of people to Stack Overflow :)
According to your comment
The first 2 numbers. It's allways a 4 digit number and I allways need to split it in 2 two digit numbers
You can simply use
$value = '0801';
$split = str_split($value, 2);
var_dump($split[0]);
var_dump($split[1]);
Just keep in mind $value variable should always be of a string type, not int.
print_r(str_split($str,"2"));