Jump to content

Recommended Posts

Hi

 

Just learning PHP and I'm struggling with a very simple problem.

 

I'm playing around with arrays as i figure they're one of the most important things to know inside out but I can't work out how to change the value of an array element via a loop. I can obviously do it if I just directly write $cars[2] = "test" but not having any luck with the loop.

 

I've tried using "foreach" and passing a new value to the $value variable but when i do a print_r the values in the array are unchanged.

 




$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";



foreach ($cars as $key => $value)
  {

$value = "TEST";
echo $key . " " . $value . "<br />";

  }

print_r($cars)

 

 

I then tried using a for loop

 

for ($i=0; $i <= count($cars); $i++)

{

echo $cars[$i];

$cars[$i] = "2";


}

 

But this code just threw up a fatal error as follows:

 

"Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 16 bytes) in /home/zzzzzzzz/public_html/php_testing/arrays.php on line 27"

 

So would someone be kind enough to explain where i'm going wrong and why i get the fatal error on the second for loop.

 

Thanks

 

Drongo

Link to comment
https://forums.phpfreaks.com/topic/229714-changing-array-values/
Share on other sites

$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";



foreach ($cars as $key => $value)
  {

$cars[$key] = "TEST"; //change the value.
echo $key . " " . $value . "<br />"; //this will still output Saab, BMW, Toyota, etc.  Because the value of "$value" has already been set, before we alter it.

  }

echo '<pre>'; print_r($cars); echo '</pre>';//this should print an array full of "TEST".

AND

for ($i=0; $i < count($cars); $i++) {
echo $cars[$i]; //this should print your array Saab, BMW, Toyota, etc.

$cars[$i] = 2; //we now change the value of the array to 2.
}
echo '<pre>'; print_r($cars); echo '</pre>';//should show that cars is an array full of 2's.

 

That should clear it up.  Let us know.

Hi Jcbones

 

Well your tweaks worked a treat and I think I now see where I was going wrong.

 

Sorry to post with such a simple one but I really couldn't find an answer on google and I was feeling slightly demoralised by getting stuck at such a simple hurdle - I suppose you have to start somewhere! :)

 

Thanks for your help!

 

Drongo

 

 

$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";



foreach ($cars as $key => $value)
  {

$cars[$key] = "TEST"; //change the value.
echo $key . " " . $value . "<br />"; //this will still output Saab, BMW, Toyota, etc.  Because the value of "$value" has already been set, before we alter it.

  }

echo '<pre>'; print_r($cars); echo '</pre>';//this should print an array full of "TEST".

AND

for ($i=0; $i < count($cars); $i++) {
echo $cars[$i]; //this should print your array Saab, BMW, Toyota, etc.

$cars[$i] = 2; //we now change the value of the array to 2.
}
echo '<pre>'; print_r($cars); echo '</pre>';//should show that cars is an array full of 2's.

 

That should clear it up.  Let us know.

In PHP 5, you can use a reference in the foreach:

$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";

foreach ($cars as $key => &$value)  // <-- $value is a reference
{
  $value = "TEST";
  echo $key . " " . $value . "<br />";
}

You have to watch out though. After the loop, $value still references the last element of the array. So if you use $value again, you could overwrite the array value. It is best to unset $value immediately after the loop.

$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";

foreach ($cars as $key => &$value)  // <-- $value is a reference
{
  $value = "TEST";
  echo $key . " " . $value . "<br />";
}
// Get rid of the reference
// unset($value); // without this line we're borked.

// more code

$value = someCalculationFunction();
// NOW we have changed $cars[3]. OOPS!

 

 

Your other example was running in an infinite loop because of the <= which should have been just <.

 

for ($i=0; $i <= count($cars); $i++)
{
  echo $cars[$i];
  $cars[$i] = "2";
}

 

The loop condition is evaluated every time through the loop. When it started count($cars) was 4. After processing $i=3 and incrementing $i; it is now 4 which is LESS THAN OR EQUAL TO 4, so it ran again. This time, we added an element $cars[4]. So the test is $i (which is 4) is less than or equal to count($cars) (which is 5 now), so it continued to run. Since the array indexes start at zero, you need to use $i < count($cars). However, using count() as the condition adds extra work since the array is counted every time the loop repeats. It is more efficient to capture the count before the loop (oh, and use less than):

 

$times = count($cars);
for ($i=0; $i < $times; $i++)
{
  echo $cars[$i];
  $cars[$i] = "2";
}

Thanks David

 

Really helpful explanation. I'm ensuring a sharp learning curve but the fundamentals are starting to click into place. Thanks for your help!

 

In PHP 5, you can use a reference in the foreach:

$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";

foreach ($cars as $key => &$value)  // <-- $value is a reference
{
  $value = "TEST";
  echo $key . " " . $value . "<br />";
}

You have to watch out though. After the loop, $value still references the last element of the array. So if you use $value again, you could overwrite the array value. It is best to unset $value immediately after the loop.

$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";

foreach ($cars as $key => &$value)  // <-- $value is a reference
{
  $value = "TEST";
  echo $key . " " . $value . "<br />";
}
// Get rid of the reference
// unset($value); // without this line we're borked.

// more code

$value = someCalculationFunction();
// NOW we have changed $cars[3]. OOPS!

 

 

Your other example was running in an infinite loop because of the <= which should have been just <.

 

for ($i=0; $i <= count($cars); $i++)
{
  echo $cars[$i];
  $cars[$i] = "2";
}

 

The loop condition is evaluated every time through the loop. When it started count($cars) was 4. After processing $i=3 and incrementing $i; it is now 4 which is LESS THAN OR EQUAL TO 4, so it ran again. This time, we added an element $cars[4]. So the test is $i (which is 4) is less than or equal to count($cars) (which is 5 now), so it continued to run. Since the array indexes start at zero, you need to use $i < count($cars). However, using count() as the condition adds extra work since the array is counted every time the loop repeats. It is more efficient to capture the count before the loop (oh, and use less than):

 

$times = count($cars);
for ($i=0; $i < $times; $i++)
{
  echo $cars[$i];
  $cars[$i] = "2";
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.