1

i'm realy done with this. My problem is the following:

code:

<?php
$highest = 0;
$string = "a.1";

$array = explode(".",$string);
$highest = $array[1];

$final = "secound value is: ".$highest++;

echo $final;
?>

All i want is adding something to the number in the $string. So as a result it should echo 2. However it echos 1.

Whats wrong?

1
  • 5
    Because it gets incremented after you assign it to the variable. Change post $highest++ increment, to ++$highest Commented Jul 12, 2016 at 14:56

5 Answers 5

4

Use pre-increment:

$final = "secound value is: ".++$highest;

More info: Incrementing/Decrementing Operators

Sign up to request clarification or add additional context in comments.

2 Comments

what is the difference? I never knew that there is something like this. Thats it. Thank you!
@Johrdon, The reason is there in my answer
1

Try the below code

<?php
$highest = 0;
$string = "a.1";

$array = explode(".",$string);
$highest = $array[1];

$final = "secound value is: ". ++$highest;

echo $final;
?>

The reason is, $highest++ is the post-increment. It will increment the value only after its usage. And ++$highest is pre-increment will increment the value first and then use it

Comments

1

You are doing a post increment. If you do a pre-increment, you will get 2 as your result. Is this what you want?

$final = "secound value is: ".++$highest;

Comments

1

Just to put an answer out of the box. You can save yourself exploding and an array that you may not need/want.

$highest = substr($str, 2) + 1;

2 Comments

I tried to use this, but the result is $highest1, the adding operations create a concatenation instead of adding.
@LuigiLopez I just double checked $string = "a.1"; $highest = substr($string, 2) + 1; echo $highest; and echoed 2 out. In php + cannot be used for string concatenation only the ..
0

There is a difference between pre-increment and post increment.

pre-increment-(++$highest)
   At first increase the value by one then executes the statement.
post-increment-($highest++)
   At first executes the statement then increase the value by one.

So in this case You have to use pre-increment.Then line will be executed after increment of the value .

Try this code:

<?php
$highest = 0;
$string = "a.1";

$array = explode(".",$string);
$highest = $array[1];

$final = "secound value is: ".++$highest;

echo $final;
?>

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.