substring and arrays

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
hob_goblin
Forum Regular
Posts: 978
Joined: Sun Apr 28, 2002 9:53 pm
Contact:

substring and arrays

Post by hob_goblin »

how would i implode a string of numbers, by the lenght.. like

if i had

123456789

and i wanted it to take 3 numbers and create an array.. like

123 - 456 - 789

how would i do that?
i tried to use a for() loop, but it seems that if i did
for($i = 0; $i < $thing; $i+3){}
it wouldn't work...

any ideas?
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

Code: Select all

$source = "123456789";
$source=number_format($source);
$arr = explode(',', $source);
foreach($arr as $ns)
	print($ns.'<br/>');
will do it for numbers
User avatar
hob_goblin
Forum Regular
Posts: 978
Joined: Sun Apr 28, 2002 9:53 pm
Contact:

Post by hob_goblin »

ahh, now... let me try it, it should work, because i am working with numbers...

thanks
User avatar
hob_goblin
Forum Regular
Posts: 978
Joined: Sun Apr 28, 2002 9:53 pm
Contact:

Post by hob_goblin »

well, that didn't... because there is no argument to set the width of the commas... three was just an example, i really want more ( 8 )
User avatar
RandomEngy
Forum Contributor
Posts: 173
Joined: Wed Jun 26, 2002 3:24 pm
Contact:

Post by RandomEngy »

Just wrote this script:

Code: Select all

<?php

$input = "14539592348725";
$segment_len = 4;
$result = array();
for( $i = 0; $i < strlen($input); $i += $segment_len)
  $result&#1111;] = substr($input, $i, $segment_len);

echo "<pre>";
var_dump($result);
echo "</pre>";

?>
User avatar
hob_goblin
Forum Regular
Posts: 978
Joined: Sun Apr 28, 2002 9:53 pm
Contact:

Post by hob_goblin »

i fixed it by doing this:

Code: Select all

for($i = 0; $i < $thing; $i++)&#123;
$x = $i * 8;
$sub = substr($foo, $x, 8);
$arr&#1111;] = $sub;
&#125;
Post Reply