php array question

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
Wootah
Forum Newbie
Posts: 13
Joined: Wed Jul 14, 2010 7:08 pm

php array question

Post by Wootah »

Suppose you have a multi-dimensional array but want to work with just one dimension of that array.
Without looping, how can I easily get that one dimension into a new array to work on?

I am used to presuming there is some awesome function with php that I don't know exists just yet....

The reason is that a function wants an input parameter to be an array of a certain type.

Thanks!!
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: php array question

Post by requinix »

Which dimension? The first? That's just $array[X]. Too easy. So the second?

Code: Select all

$first = array(
	array(0, 1, 2, 3, 4, 5),
	array(0, 2, 4, 6, 8, 10),
	array(0, 3, 6, 9, 12, 15),
	array(0, 4, 8, 12, 16, 20)
);

// PHP <5.3 {
function pick(array $second) { return $second[5]; }
$array = array_map("pick", $first);
// }

// PHP 5.3 {
$array = array_map(function($second) {
	return $second[5];
}, $first);
// }
Wootah
Forum Newbie
Posts: 13
Joined: Wed Jul 14, 2010 7:08 pm

Re: php array question

Post by Wootah »

Code: Select all

$first = ((1 2 3 ),(4 5 6),(7 8 9),....)
Now i want an an array of (1 4 7) the first element of each sub array.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: php array question

Post by requinix »

Right, I figured as much. Which is what the code I posted does.
Post Reply