Travis Low wrote:

Hi Katie,

The foreach construct operates on copies of the array values. I usually just stick to C-like syntax:

for( $i = 0; $i < count( $array ); $i++ )
{
    $array[$i] = doSomething( $array[$i] );
}

Remember that this will only work for consecutively integer indexed arrays. If you're missing an index or are using an associative array, this won't work.


Ex1:

$array = array(0 => 0, 1 => 1, 3 => 2);

If you use the above method, you never get to the 3 index. Actually, you would end up with a 2 => soemthing in there that wasn't originally in there.

Ex2:

$array = array('a' => 'some', 'b' => 'thing');

Running the above on this array will create a 0 and 1 index with something in them while not affecting the values actually in there. If you want to make sure that your code will always work with any arraym use one of the following:

foreach($array as $key => $value) {
  $array[$key] = doSomething($value);
}

foreach(array_keys($array) as $key) {
  $array[$key] = doSomething($array[$key]);
}


cheers,


Travis

Katie Marquez wrote:

I'm practicing from a beginning PHP book regarding
arrays and the PHP manual, so please no one flame me
that I didn't try to research before posting.  I'm
thinking that what I want to do requires me to use the
function array_walk or a foreach loop, but I'm not so
sure so maybe someone help here can help.

I want to have an array, perform an action on the
values in the array, and have those actions
permanently affect the values in the array.  Here's
something I've written to test it out how I thought it
could be done:

<?php
    $array = ('zero\0', 'one\1', 'two\2', 'three\3');
    // look at array before changes
    print_r($array);
    // maybe use foreach or array_walk next?
    foreach ($array as $value)
    {
         stripslashes($value);
    }
    // look at array after changes
    print_r($array);
?>

I'm guessing by now someone can see my error, but I
don't know enough programming to spot it.  What I
thought would happen is my values would have the
backslash removed in the second print_r().  What I
would want is for any changes made in the array
(meaning my "values") to be permanent in the array
afterwards.  If I can accomplish the code above, I
figure I can create my own functions to affect changes
on values or at least better understand what I'm
looking at in other people's examples/comments at the
online PHP manual.

Thank you in advance.

Katie


__________________________________
Do you Yahoo!?
Win a $20,000 Career Makeover at Yahoo! HotJobs http://hotjobs.sweepstakes.yahoo.com/careermakeover




--
paperCrane <Justin Patrin>

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Reply via email to