Page 1 of 1

using each() to modify array contents

Posted: Fri Sep 17, 2004 12:14 pm
by zkajan
Hello
I'm new to PHP so I'm probably making a simple blunder here and I don't even realize it. Anyways, I have an array that is filled with several subarrays. I want to make a copy of it, but don't want the copy to have all of the subarrays, just the first four from each entry. I thought the following code would do it, and when I sprinkle print_rs through it it seems to be doing it, except at the very end I still have the same array at hand (it didnt' really do anything). Any and all help is appreciated.

Code: Select all

$retVal = $gaugeArrayToTrim;
reset($retVal);//sets key to begining
while (list($key, $value) = each($retVal))
{	
	$tempholder = $value;
	$value = array_slice($tempholder, 0, 4);
}

Posted: Fri Sep 17, 2004 12:37 pm
by markl999

Code: Select all

<?php

$array = array(
  array('a', 'b', 'c', 'd', 'e', 'f'),
  array(1, 2, 3, 4, 5, 6, 7),
  array('z', 'y', 'x', 'w', 'v', 'u')
);
while (list($key, $val) = each($array)) {
  $array[$key] = array_slice($val, 0, 4);
}
echo '<pre>';
var_dump($array);
echo '</pre>';

?>

Posted: Fri Sep 17, 2004 12:46 pm
by zkajan
yes, i know what array_slice does, but what i wanted to do was modify subarrays, as in

Code: Select all

$array = array(&#1111;0] => array('a', 'b', 'c', 'd'), &#1111;1] =>  array('e', 'f', 'g', 'h'));
and now wanting to make a copy of $array that still has elements 0 and 1 but they contain a and b, and e and f respectively.

Anyways, I have since posting figured out how to do it. I think writing it out helped me formulate what I was trying to accomplish.

Code: Select all

foreach ($gaugeArrayToTrim as $key => $value)
&#123;
	$retVal&#1111;$key] = array_slice($gaugeArrayToTrim&#1111;$key], 0, 4);
&#125;
return $retVal;

Posted: Fri Sep 17, 2004 12:50 pm
by markl999
That's exactly what my code did :o
It loops over the arrays and extracts the first 4 elements of each sub array and uses them to rebuild the original array.
Our code is almost identical, but you have $gaugeArrayToTrim[$key] .. which is actually $value (i used $val in mine).

Posted: Fri Sep 17, 2004 2:48 pm
by zkajan
oh oh i see it now, sorry
the missing of subbarrays is why i thought it was different

thanks for you help though