...

View Full Version : increment an array's index



Gabarieko
08-12-2008, 08:13 PM
I have an
$arr = explode("|", $str);
from wich i need to display all of it's values. ($arr['0'] ; $arr['1'] ...)
I cant know the number of $arr's parts for shure. Thats why I tryed Repeating()

function Repeating($count)
{
for ($i=0;$i<=$count;$i++)
{
$r="$arr[' ".$i." ']";
echo $r;
}
}
Unfortenetly this doesn't work becouse "echo $r;" gets the value of $r and not further (to the value of the variable formed in $r)

Thx for any idias :thumbsup:

Brandoe85
08-12-2008, 08:24 PM
Loop through the array - take a look at foreach:
http://us3.php.net/foreach

If you need to get the number of elements in the array look at count():
http://us3.php.net/count

Good luck;

Fou-Lu
08-12-2008, 08:25 PM
You're function requires that it be given an array, and that $arr is available for the function. You can do this by either globalizing the $arr or by passing it in as an argument (recommended).


function Repeater($arr)
{
$count = count($arr);
for ($i = 0; $i < $count; $i++)
{
$r = $arr[$i];
echo $r . "\n";
}
}
// Or
function Repeater()
{
global $sameArrayName;
$count = count($sameArrayName);
for ($i = 0; $i < $count; $i++)
{
$r = $sameArrayName[$i];
echo $r . "\n";
}
}

Since the name has to be the same, this is one of the reasons why passing it as an argument is recommended. Another option is a foreach loop, which allows you to separate the key / value pairs, and works on arrays with associated string keys:


foreach ($arr AS $key => $val) // Or foreach ($arr AS $val)
{
printf("The value at index &#37;s is %s\n", $key, $val);
}

For loop does not work (as shown above) on string indexed values. This doesn't mean you cannot make it work, but a foreach really simplifies the process. The only requirement is that you should ensure that $arr is an array with is_array($arr) before performing the foreach, otherwise it will trigger a notice.

Hope that helps!


Bah, beaten by Brandoe :P
Back to ASP with you :D

Brandoe85
08-12-2008, 08:31 PM
lol your reply is much more descriptive though!

Gabarieko
08-12-2008, 09:12 PM
It realy helped a lot!
Thanks for the great post. I now saw my mistake :)

(It works great)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum