0

I have string. for example

$string = 1234567; 

or

$string = 1976324  

How i can split each second. for example.

[0=>1357, 1=>246];

or

[0=>1734, 1=>962];
1

2 Answers 2

1

You could also use a combination of str_split, array_chunk and array_column.
I am not recommending this, rather presenting another, alternate way of processing this that gave me some fun ;)

Note : array_column() requires PHP 5.5+.

Example Code :

php > $string = 1234567;
php > print_r(array_column(array_chunk(str_split($string, 1), 2), 0));
Array
(
    [0] => 1
    [1] => 3
    [2] => 5
    [3] => 7
)
php > print_r(array_column(array_chunk(str_split($string, 1), 2), 1));
Array
(
    [0] => 2
    [1] => 4
    [2] => 6
)

Of course you may also concatenate that into strings:

php > echo implode('', array_column(array_chunk(str_split($string, 1), 2), 1));
246
php > echo implode('', array_column(array_chunk(str_split($string, 1), 2), 0));
1357
Sign up to request clarification or add additional context in comments.

1 Comment

your answer not so good because eating extra resources. you calling twice 4 functions. for each iteration
1

You can do this way:

<?php
$string = 1234567; 
$string = (string)$string;
$tmp[0] = "";
$tmp[1] = "";
for($i = 0; $i < strlen($string);$i++)
{
  if($i % 2)
  {
   $tmp[1] .= $string[$i];  
  }
  else
  {
   $tmp[0] .= $string[$i];
  }

}

print_r($tmp);
?>

1 Comment

If you ever edit this answer please also include an educational explanation. Not every dev knows what the modulus operator does.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.