0

this must be very simple but I couldn't make it work.. PHP noob :P

I have this array "$e_cats" and when I do var_dump($e_cats); the result is this:

array(3) { [0]=> string(3) "192" [1]=> string(3) "190" [2]=> string(3) "191" }

What I want is to add "-" to every value inside, so "-192", "-190", and "-191". Here is my code:

foreach ($e_cats as $cat) {
    $cat = '-' .$cat;
}

but when I do print_r($cat) the result is: -191 (not all values). What did I do wrong?

Thanks in advance

5
  • use foreach ($e_cats as &$cat) instead of foreach ($e_cats as $cat). Commented Jun 19, 2013 at 22:20
  • HamZa, thanks mate, but it doesn't work. foreach ($e_cats as &$cat) { $cat = '-' .$cat; } print_r($cat); result = -191 Commented Jun 19, 2013 at 22:22
  • Look over the part near the top of the foreach docs about modifying array elements by reference. Commented Jun 19, 2013 at 22:22
  • @Mario88 See it working, or am I missing something ? Commented Jun 19, 2013 at 22:26
  • Unless you really need these as strings, PHP will cast them to ints so you can just do $cat = -$cat; !! Commented Jun 19, 2013 at 22:26

1 Answer 1

1
foreach($e_cats as $i => $cat) {
    $e_cats[$i] = '-' . $cat;
}

You were close!

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.