0

I got an array with values splits to 5 arrays with groups of 3 values, then I got more group of array of pointers, what I'm trying to do is replacing the pointed array with other value.

what I got is :

$a = array(["4", "3", "5"], ["4", "8", "11"], ["4", "11", "5"], ["4", "5", "5"], ["4", "4", "9"]);

$b = array(12); // the value to be placed

$pointers = array([1,2],[2,2],[2,1]);

foreach($pointers as $point)
{
    $a1 = array_replace($a[$point[0]], array($point[1] => $b ));
}

Expected results:

["4", "3", "5"], ["4", "8", "12"], ["4", "12", "12"], ["4", "5", "5"], ["4", "4", "9"]

What I need is to keep the array structure as is and just replace the pointed values to be 12.

I'm not sure its the right way.

8
  • PHP doesn't have pointers. Do you mean array indexes? Commented Jul 31, 2022 at 20:03
  • i just called it pointers , yes its indexes :) Commented Jul 31, 2022 at 20:03
  • You're overwriting $a1 each time through the loop. The result will just be the replacement from the last element of $pointer. Commented Jul 31, 2022 at 20:06
  • Why is $b an array? That will create a nested array in the replacement. Commented Jul 31, 2022 at 20:08
  • because array_replace needs arrays i think Commented Jul 31, 2022 at 20:09

1 Answer 1

1

You don't need to use array_replace(), just assign using the indexes in $pointers.

$a = array(["4", "3", "5"], ["4", "8", "11"], ["4", "11", "5"], ["4", "5", "5"], ["4", "4", "9"]);
$b = 12; // the value to be placed
$pointers = array([1,2],[2,2],[2,1]);

foreach($pointers as [$p1, $p2])
{
    $a[$p1][$p2] = $b;
}
print_r($a);
Sign up to request clarification or add additional context in comments.

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.