1

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?

5
  • What determines the split? Position? (I.e always the first 2 etc.c) Value? your question is vague. Commented Dec 17, 2015 at 16:10
  • The first 2 numbers. It's allways a 4 digit number and I allways need to split it in 2 two digit numbers, Commented Dec 17, 2015 at 16:11
  • php.net/manual/en/function.substr.php Commented Dec 17, 2015 at 16:13
  • use if always the first 2 print_r(str_split($str,"2")); Commented Dec 17, 2015 at 16:14
  • Oh damn. Thank you a lot, Commented Dec 17, 2015 at 16:14

4 Answers 4

1

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";
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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 :)
1

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.

Comments

1

you can use str_split and list

$str = '0801';
list($first,$second) = str_split($str,2);

echo $first;
// 08
echo $second;
// 01

Comments

1

No one gave a MySQL answer yet...

If you're selecting that number..

SELECT 
    SUBSTR(colname, 0, 2) as firstpart, 
    SUBSTR(colname, 2, 2) as secondpart 
FROM table

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.