Forum Moderators: coopster

Message Too Old, No Replies

Limiting an Array

How to display a few bits...

         

ahmedtheking

4:01 pm on Mar 23, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Is it possible to limit an array?

For example to display parts of an array (that has say 22 bits to it) but only display 4 bits of it?

mincklerstraat

4:20 pm on Mar 23, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



check out array_slice() and don't forget foreach(), which is a control structure bound to an array - handiest thing since sliced bread.
foreach($array as $key => $value){
if($key > 4 AND $key < 9) echo $value;
}

ahmedtheking

4:36 pm on Mar 23, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



wot value would $key be?

mincklerstraat

5:19 pm on Mar 23, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Arrays always consist of keys and values, although the keys are sometimes 'implicit' and never really used explicitly. If you make an array:

$array = array('moo', 'cow', 'moo');

you can see what the keys are by doing:

echo '<pre>';
print_r($array);
echo '</pre>';

Output would look something like this:

array(
0 => 'moo',
1 => 'cow',
2 => 'moo');

This means the keys are 0, 1, and 2 - this is how keys are 'automatically' generated for arrays that aren't 'associative' arrays - that is, arrays where you explicitly state what the keys are.

You could have also made an array with the same values, but stipulating what the keys are - which will behave differently depending on what you do with it:


$array = array('sound' => 'moo', 'animal' => 'cow', 'name' => 'moo');

The code I gave you above will only work if you have a non-associative array - i.e., one you didn't set the keys on yourself, so each '$key' has a number that can be measured.

ahmedtheking

5:34 pm on Mar 23, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Ok, I tried that foreach loop, but it gave 'Array'! :S

mincklerstraat

5:55 pm on Mar 23, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



An array can contain lots of stuff - including other arrays. This means that in all likelihood your array does't have just plain 'scalar' values (things like integers, numbers with decimal places (floats), strings, etc), but also has got an array or two in it. And an array can't be simply 'echo'd'.
Try
echo '<pre>';
print_r($array);
echo '</pre';

And you can see what's inside your array. You'd do well, too, to find a tutorial or something to help wrap your brain around arrays - the first time you use them they can be tricky - but later you can't live without them, you'll be using them without even thinking about it.