How to edit item by it's pointer?

<?php

$array = array(0, 1, 2, 3, 4, 5);

foreach ($array as $item) {
	$item *= 2;
}

var_dump($array);

?>

I thought I could add & just like in C, but that doesn’t seem to work.

Returns: 0, 1, 2, 3, 4, 5.
Expected: 0, 2, 4, 6, 8, 10.

Is there a real way in PHP, without going array[0] through array[5]?

Something like?

<?php

$array = array(0, 1, 2, 3, 4, 5);

foreach ($array as $key => $value) {
	$array[$key] = $value * 2;
}

var_dump($array);

?>
1 Like

I had that kind of in mind, but it will get extremely complicated with my situation (multiple levels what not).

Is there no referencing possibility in PHP?

Maybe this?

1 Like

foreach ($array as &$item) works as expected. but that has nothing to do with reducing your loop. and i don’t see anything coplicated with using the key.

1 Like

Keep in mind: there are no pointers in PHP, only references. Using the & symbol in front of a variable will tell PHP it should be passed as a reference.

In my opinion, the cleanest way to do this is using the array_map function, like @SamA74 pointed out.

1 Like

How would that look?

<?php

function double($n) { return ($n * 2) ; }

$array = array(0, 1, 2, 3, 4, 5);

$array = array_map("double", $array) ;

var_dump($array);

?>
1 Like

That’s a possible way, but I prefer the more shorthand method.

<?php

$values = [0, 1, 2, 3, 4];

$doubleValues = array_map(function ($value) {
    return $value * 2;
}, $values);

The upside of your example would be that the double function can be reused. I suppose however that’s just a dummy example.

Edit - a few code style tips:

  • You can use [ ] as a shorthand for array().
  • You don’t have to use the closing ?> php tag in .php files. It’s actually recommended not to use it to avoid unforseen results, because things after the closing tag could mess stuff up.
2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.