0

I have the following scenario:

$starterArray = array ('192.168.3.41:8013'=>0,'192.168.3.41:8023'=>0,'192.168.3.41:8033'=>0);

In the requirement I have another array which counts some events of the application, this array uses the same keys as my first array, but values can change), so at the end I could have something like:

$processArray = array ('192.168.3.41:8013'=>3,'192.168.3.41:8023'=>5,'192.168.3.41:8033'=>7);

I want to update the values of my starter array with the values of the process array, for instance, at the end, I should have:

$starterArray = array ('192.168.3.41:8013'=>3,'192.168.3.41:8023'=>5,'192.168.3.41:8033'=>7);

I know this can be achieved by using $starterArray = $processArray;

Then in some moments, I would need to sum some units to the values of my array, for example +1 or +2:

It should be something like the following?

foreach ($starterArray as $key => $value) {
    $starterArray[$value] = $starterArray[$value]+1;
}

Then, for my process array, I need to set the values to 0

foreach ($processArray as $key => $value) {
    $processArray[$value] = 0;
}

This is what I tried but it is not working, if somebody could help me I will really appreaciate it. Thanks in advance.

PD: I know these are strange requirements, but that's what I am asked to do...

1
  • 1
    The PHP manual has examples for foreach that should help you. In particular, you are using [$value] instead of [$key]. Commented Jun 14, 2013 at 21:52

3 Answers 3

1

You are almost there:-

foreach ($processArray as $key => $value) {
    $starterArray[$key] = $value +1;
}

and then:-

foreach ($processArray as $key => $value) {
    $processArray[$key] = 0;
}

However, you could do this all in one loop:-

foreach ($processArray as $key => $value) {
    $starterArray[$key] = $value +1;
    $processArray[$key] = 0;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You need to put $key in brackets, not $value.

Or, you can do:

foreach ($starterArray as $key => &$value) {
    $value++; /* put here whatever formula you want */
}

Comments

1
foreach ($starterArray as $key => $value) {
    $starterArray[$key] = $value+1;
    // or $starterArray[$key] = 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.