2

I have an two dimensional array called $array. After another question here, I know how to change the whole child array from a two dimensional array like this:

Code

$keys = array(0, 1);    
  foreach ($keys as $key) { 
      foreach ($array[$key] as $key2 => $value) {  
          $array[$key][$key2] = str_replace($stamm, $stamm2, $value);
        }
    } 

How is it possible to change only $array[0][3],$array[0][4] and $array[1]?

$array use $stamm + ending of an verb for a time for example "ons". I have to change for some cases the root of the verb ($stamm).
With the code above it works perfectly to change the whole array[0] and array[1]. .

2
  • Could you please elaborate a little on what you really intend to do ? I mean the functional part, what you are trying to achieve? Then we could probably provide a better solution / explanation Thank you Commented Jun 4, 2015 at 8:17
  • Definitly ! Thank you :) I believe some simple solutions have already been provided below. As an complement, you could also "type" your values, y that I mean making money pattern with stamms and endings. then if you work with simple objects, you can check against types which would be probably be more readable, ie : if($value instanceof Stamm) then... A little more complicated, but probably easier to read later. Commented Jun 4, 2015 at 8:29

1 Answer 1

5

Why dont you simply do this

$array[0][3] = //your value;
$array[0][4] =  //your value;  

and if you want to change all value of $array[1]:

foreach ($array[1] as $key => $value) {  
      $array[1][$key] = //your value;
    }  

EDIT to do all this with a foreach :

foreach ($keys as $key) { 
  foreach ($array[$key] as $key2 => $value) { 
      if(($key==0 && ($key2 == 3 || $key2 == 4)) || ($key == 1) ) 
          $array[$key][$key2] = //your value;
    }
} 
Sign up to request clarification or add additional context in comments.

5 Comments

Before the foreach-loop their is a if-loop. I have many, similar if-loops and I will change often some parts auf the array (conjugation script). I thought it would be shorter and more elegant to do this with foreach-loops.
Why not foreach ($array[1] as &$value) { $value = $new_value; }?
@Grischa check the EDIT part of my answer for automated solution
@LuthandoLoot Thanks this is what I was searching for. Would it be more elegant to change && ($key2 == 3 || $key2 == 4) to an array like $key2 = array(3, 4) ?
yes you can actually add your accepted values in an array like this $acceptedValues = array(1,2); then if(in_array($key2, $acceptedValues ))

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.