CoolCodeGuy
CoolCodeGuy

Reputation: 44

Adding something to the start of a variable?

I am looking for some code that allows you to add +44 onto the beginning of my $string variable.

So the ending product would be:

$string = 071111111111

+44071111111111

Upvotes: 0

Views: 66

Answers (3)

Aaron Christiansen
Aaron Christiansen

Reputation: 11807

Your $string variable isn't actually a string in this scenario; it's an integer. Make it a string by putting quotes around it:

$string = "071111111111"

Then you can use the . operator to append one string to another, so you could do this:

$string = "+44" . $string

Now $string is +44071111111111. You can read more about how to use the . (string concatenation operator) on the PHP documentation here.

Other people's suggestions of just keeping $string as an integer wouldn't work: "+44" . 071111111111 is actually +447669584457. Due to the 0 at the start of the number, PHP converts it to an octal number rather than a decimal one.

Upvotes: 1

NormundsP
NormundsP

Reputation: 413

You can use universal code, which works with another parameters too.

<?php
$code = "+44";
$string = "071111111111";


function prepend(& $string, $code) {
    $test = substr_replace($string, $code, 0, 0);
    echo $test;
}
prepend($string, $code);

?>

Upvotes: 1

Oleg Kuznecov
Oleg Kuznecov

Reputation: 11

You can combine strings by . $string = '+44'.$string;

Upvotes: 1

Related Questions