explode elements of an array

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
jaymoore_299
Forum Contributor
Posts: 128
Joined: Wed May 11, 2005 6:40 pm
Contact:

explode elements of an array

Post by jaymoore_299 »

I have an array that looks like this
("a b c", "d e f", "g h i", .. etc)
except it has over 30 elements.

What's the most efficient way to explode the elements of the array to get
something like this
m[0][0] = a
m[0][1] = b
m[0][2] = c
m[1][0] = d
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

So every 3rd element, you want to increment the 1rst indice?
SBro
Forum Commoner
Posts: 98
Joined: Tue Sep 30, 2003 10:06 pm

Post by SBro »

Try this

Code: Select all

$blah = array('a b c', 'd e f', 'g h i');

foreach ($blah as $key => $value) {
	$exp = explode(' ', $value);
	foreach ($exp as $k => $v) {
		$new[$key][$k] = $v;
	}
}
Will return the following

Code: Select all

Array
(
    ї0] => Array
        (
            ї0] => a
            ї1] => b
            ї2] => c
        )

    ї1] => Array
        (
            ї0] => d
            ї1] => e
            ї2] => f
        )

    ї2] => Array
        (
            ї0] => g
            ї1] => h
            ї2] => i
        )

)
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Too many loops for my liking ;)

Code: Select all

$letters = array("a b c", "d e f", "g h i");

foreach ($letters as $new_letter)
{
	$let_arr[] = explode(' ',$new_letter);
}

print_r($let_arr);

Code: Select all

Array
(
    ї0] => Array
        (
            ї0] => a
            ї1] => b
            ї2] => c
        )

    ї1] => Array
        (
            ї0] => d
            ї1] => e
            ї2] => f
        )

    ї2] => Array
        (
            ї0] => g
            ї1] => h
            ї2] => i
        )

)
Post Reply