Converting an integer to a string in PHP - php

Is there a way to convert an integer to a string in PHP?

You can use the strval() function to convert a number to a string.
From a maintenance perspective its obvious what you are trying to do rather than some of the other more esoteric answers. Of course, it depends on your context.
$var = 5;
// Inline variable parsing
echo "I'd like {$var} waffles"; // = I'd like 5 waffles
// String concatenation
echo "I'd like ".$var." waffles"; // I'd like 5 waffles
// The two examples above have the same end value...
// ... And so do the two below
// Explicit cast
$items = (string)$var; // $items === "5";
// Function call
$items = strval($var); // $items === "5";

There's many ways to do this.
Two examples:
$str = (string) $int;
$str = "$int";
See the PHP Manual on Types Juggling for more.

$foo = 5;
$foo = $foo . "";
Now $foo is a string.
But, you may want to get used to casting. As casting is the proper way to accomplish something of that sort:
$foo = 5;
$foo = (string)$foo;
Another way is to encapsulate in quotes:
$foo = 5;
$foo = "$foo"

There are a number of ways to "convert" an integer to a string in PHP.
The traditional computer science way would be to cast the variable as a string:
$int = 5;
$int_as_string = (string) $int;
echo $int . ' is a '. gettype($int) . "\n";
echo $int_as_string . ' is a ' . gettype($int_as_string) . "\n";
You could also take advantage of PHP's implicit type conversion and string interpolation:
$int = 5;
echo $int . ' is a '. gettype($int) . "\n";
$int_as_string = "$int";
echo $int_as_string . ' is a ' . gettype($int_as_string) . "\n";
$string_int = $int.'';
echo $int_as_string . ' is a ' . gettype($int_as_string) . "\n";
Finally, similar to the above, any function that accepts and returns a string could be used to convert and integer. Consider the following:
$int = 5;
echo $int . ' is a '. gettype($int) . "\n";
$int_as_string = trim($int);
echo $int_as_string . ' is a ' . gettype($int_as_string) . "\n";
I wouldn't recommend the final option, but I've seen code in the wild that relied on this behavior, so thought I'd pass it along.

Use:
$intValue = 1;
$string = sprintf('%d', $intValue);
Or it could be:
$string = (string)$intValue;
Or:
settype($intValue, 'string');

Warning: the below answer is based on the wrong premise. Casting 0 number to string always returns string "0", making the code provided redundant.
All these answers are great, but they all return you an empty string if the value is zero.
Try the following:
$v = 0;
$s = (string)$v ? (string)$v : "0";

There are many possible conversion ways:
$input => 123
sprintf('%d',$input) => 123
(string)$input => 123
strval($input) => 123
settype($input, "string") => 123

You can either use the period operator and concatenate a string to it (and it will be type casted to a string):
$integer = 93;
$stringedInt = $integer . "";
Or, more correctly, you can just type cast the integer to a string:
$integer = 93;
$stringedInt = (string) $integer;

As the answers here demonstrates nicely, yes, there are several ways. However, in PHP you rarely actually need to do that. The "dogmatic way" to write PHP is to rely on the language's loose typing system, which will transparently coerce the type as needed. For integer values, this is usually without trouble. You should be very careful with floating point values, though.

I would say it depends on the context. strval() or the casting operator (string) could be used. However, in most cases PHP will decide what's good for you if, for example, you use it with echo or printf...
One small note: die() needs a string and won't show any int :)

$amount = 2351.25;
$str_amount = "2351.25";
$strCorrectAmount = "$amount";
echo gettype($strCorrectAmount); //string
So the echo will be return string.

My situation :
echo strval("12"); => 12
echo strval("0"); => "0"
I'm working ...
$a = "12";
$b = "0";
echo $a * 1; => 12
echo $b * 1; => 0

I tried all the methods above yet I got "array to string conversion" error when I embedded the value in another string. If you have the same problem with me try the implode() function.
example:
$integer = 0;
$id = implode($integer);
$text = "Your user ID is: ".$id ;

You can simply use the following:
$intVal = 5;
$strVal = trim($intVal);

$integer = 93;
$stringedInt = $integer.'';
is faster than
$integer = 93;
$stringedInt = $integer."";

Related

Php check exist have how many random int numbers in string

I have rand function like;
$mynumbers = rand(1111,9999);
echo $mynumbers;
Example output is
3582
and I have another strings
$mystring = "Ja9Js78I4PhXiF464R6s7ov8IUF"; (Have 1 number, must be turn 1 (only 8 have))
$mystring2 = "Ja3Js73I4P1X5iF564R8s2ov8IUF"; (Have 4 numbers, must be turn 4 (have all of them))
And i want to know this with function ;
$mystring is have, how many numbers ? inside $mynumbers and how many time ? passed when this process ? How can i do it ?
per your last comment. Treat the integer as a string (PHP is good at that). And iterate by character.
<?php
$foo = '1234';
$mystring = [];
$mystring[] = 'A1B2KLDLDF3'; //3
$mystring[] = 'XXXX4XXXX'; //1
foreach ($mystring as $key => $string) {
echo "mystring {$key}: ";
$c = 0;
foreach(str_split($foo) as $char) {
$c = $c + substr_count($string, $char);
}
echo $c . '<br/>';
}
mystring 0: 3
mystring 1: 1
As this is PHP you also need to be aware of mb_ multibyte functions. See: http://php.net/manual/en/function.mb-substr-count.php
Update:
Sounds like you should clean up the string you are checking then if you want to discard all duplicates... Could then of course use a substr or other method perhaps more performant than substr_count.
$mystring = 'A111111B2KLDLDF333'; //3
$mystring = implode('',array_unique(str_split($mystring)));
//gives 'A1B2KLDF3'

How to make a string in quotes from integer in php?

How to do make a string in quotes from integer in better way in php?
$number = 1;
$number = "'" . $number . "'";
result is '1', which is good, but can it be done more nicely? I tried (string) $number but result was just 1 not '1'.
$num = 1221;
echo $numStr = "'$num'";
Results: '1221'
You can also try:
$num = 1221;
echo $numStr = "'$num'"; // output: '1221'
var_dump($strVal); // output: string(4) "1221"

How to put operators in array?

I want to make simple program that change operators "+", "-", "*", "/" for some numbers. So, I put operators in array, and try to iterate them through loop.
$num1 = 10;
$num2 = 20;
$operators = array("+", "-", "*", "/");
for ($x=0;$x<=count($operators)-1;$x++){
echo $num1 . $operators[$x] . $num2 . "</br>";
}
It displays:
10+5
10-5
10*5
10/5
That seems ok, at first glance, but I need numbers to be calculated, operations performed, simply, I need final result numbers, and this gives me 4 strings. I understand reason for this: my values in $operators array are strings, not real operators. My question is, how to put real operators in array, or maybe, I can keep them as strings in array, but somehow convert them in real operators at the output? Solutions for both strategies are welcome. Thanks in advance!
perhaps you could try somehting along the following lines:
for ( $x=0; $x < count($operators); $x++ ){
switch($operators[$x]){
case '+':$answer=$num1+$num2;break;
case'-':$answer=$num1-$num2;break;
case '*':$answer=$num1*$num2;break;
case'/':$answer=$num1/$num2;break;
}
echo $answer;
}
You can't put real operators in array as it's language contructions. But you can put functions like that (I use anonymous functions, you can use named)
$operations = array(
'+' => function ($a, $b) { return $a + $b; }
);
foreach ($operations as $sign => $func) {
echo '10'.$sign.'5 = '. $func(10, 5)."\n";
}
You may try this
$num1 = 10;
$num2 = 20;
$operators = array("+", "-", "*", "/");
for ($x=0;$x<=count($operators)-1;$x++){
echo eval('return '.$num1 . $operators[$x] . $num2 . ';')."</br>";
}

php, sessions, arrays - how to assign strign to the end of the session array

I have this small code , why it does not work and how to make it correctly ?
$temp = $_SESSION['contactPersonInterest'][$i];
$temp += ',Medlemskort';
//$_SESSION['contactPersonInterest'][$i] = $temp;
I am testing it with
?><script>alert('<?php echo $_SESSION['contactPersonInterest'][$i] ?>'+'----------'+'<?php echo $temp ?>');</script> <?php
And what i get is :
blbla,blll----------0
Whats wrong ?
Thank you
String concatenation is done with . in PHP. Try:
$temp .= ',Medlemskort';
Otherwise you perform addition, and if both strings don't start with numbers, they will be converted to 0 and 0 + 0 = 0 :)
Have a look at Type Juggling.
That's because += is an operator for adding integers, not strings. You want to concatenate strings (which is "."). Also, there is no need to create a temporary variable, only to overwrite the existing one. This should work:
$_SESSION['contactPersonInterest'][$i] .= ',Medlemskort';
You wrongly assign more things to the variable via +. You should use . instead.
$temp .= ',Medlemskort';
If you want $i to have temp's value, no need for the +=:
$temp = ""; // good habit to initialize before usage
$temp = $_SESSION['contactPersonInterest'][$i];
$temp = ',Medlemskort';
$_SESSION['contactPersonInterest'][$i] = $temp;
// or even save a $temp
$_SESSION['contactPersonInterest'][$i] = ',Medlemskort';
Hope this makes sense, good-luck

String concatenation vs array implode in PHP

Having used Java for a long time my standard method for creating long strings piece by piece was to add the elements to an array and then implode the array.
$out[] = 'a';
$out[] = 'b';
echo implode('', $out);
But then with a lot of data.
The (standard PHP) alternative is to use string concatenation.
$out = 'a';
$out .= 'b';
echo $out;
To my surprise there seems to be no speed difference between both methods. When there is significant time difference usually it is the concatenation that seems faster, but not all of the time.
So my question is: are there - apart from style and code readability - any other reasons to choose one approach over the other?
To me, using an array implies that you're going to do something that can't be done with simple string concatenation. Like sorting, checking for uniqueness, etc. If you're not doing anything like that, then string concatenation will be easier to read in a year or two by someone who doesn't know the code. They won't have to wonder whether the array is going to be manipulated before imploded.
That said, I take the imploded array approach when I need to build up a string with commas or " and " between words.
Choose the more readable one. Always. This case, i would pick up the second apporach.
Then optimize it, if it's a bottleneck.
One (subtle) difference is clearly visible when generating a character-seperated string:
<?php
$out[] = 'a';
$out[] = 'b';
echo implode(',', $out);
foreach($out as $o) {
echo $o . ',';
}
?>
The first one will print a,b where the latter will print a,b,. So unless you're using an empty string as a seperator, as you did in your example, it's usually preferred to use implode().
The concatenation-vs-implode holy war aside: No, there is no difference.
Here is a performance test for both approaches:
<?php
const M = 1000000;
// Imploding method
$start = microtime(true);
$arr = [];
for ($i = 0; $i < M; $i++) {
$arr[] = chr(65 + ($i & 0x7));
}
$str1 = implode('', $arr);
$time1 = microtime(true) - $start;
// Concatenation method
$start = microtime(true);
$str2 = '';
for ($i = 0; $i < M; $i++) {
$str2 .= chr(65 + ($i & 0x7));
}
$time2 = microtime(true) - $start;
assert( $str1 == $str2 );
echo "Time 1: $time1\n";
echo "Time 2: $time2\n";
Output with PHP 7.1.33 on MacOS:
Time 1: 0.121246
Time 2: 0.059228
Output with PHP 8.0.5 on a (slow) Debian:
Time 1: 0.88076496124268
Time 2: 0.8109610080719
So, concatenation method works faster.
it depends on what you want to do with the string / array and how you create it
if you start with an array and need to sort it / manipulate certain elements, then i suggest implode
other than that i usually use concatenation

Categories