Jump to content

Add two strings together = 0 ???


raytaylornz

Recommended Posts

I have the following code and am trying to add the strings together to make a total.

The monthup and monthdown strings are extracted from a text file earlier in the script.

 

 

echo "$monthup <br>";

echo "$monthdown <br>";

$answer = $monthup + $monthdown;

echo $answer;

 

 

It outputs

 

36809697

565151504

0

 

The last line should be the other 2 added together which equals 601961201

 

Anyone got any ideas?

 

Thanks in advance for any help you can give. As you can see I am new to php.

Link to comment
https://forums.phpfreaks.com/topic/178890-add-two-strings-together-0/
Share on other sites

you could do

echo "$monthup <br>";
echo "$monthdown <br>";
$answer = (int)$monthup + (int)$monthdown;
echo $answer;

or

$monthup = (int)trim($monthup);
$monthdown = (int)trim($monthdown);
echo "$monthup <br>";
echo "$monthdown <br>";
$answer = (int)$monthup + (int)$monthdown;
echo $answer;

You may need to cast them to numbers as an integer or a real number[ use (real) instead of (int)] before adding them together. if the variable has a space before the number by accident, trim() will remove it.

PHP strings can be accessed with array operator

 

<?php

$f = "PHP Freaks";

for ($i = 0; $i < strlen($f); $i++) echo $f[$i];

That's where confusion may be coming from.

 

However, you can't do this with foreach and is_array($f); will return false.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.