• Language Reference

String Operators

There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator (' .= '), which appends the argument on the right side to the argument on the left side. Please read Assignment Operators for more information.

<?php $a = "Hello " ; $b = $a . "World!" ; // now $b contains "Hello World!" $a = "Hello " ; $a .= "World!" ; // now $a contains "Hello World!" ?>

User Contributed Notes 6 notes

To Top

PHP Tutorial

Php advanced, mysql database, php examples, php reference, php settype() function.

❮ PHP Variable Handling Reference

Convert variables to specific types:

Definition and Usage

The settype() function converts a variable to a specific type.

Parameter Values

Technical details.

Get started with your own server with Dynamic Spaces

COLOR PICKER

colorpicker

Get your certification today!

set string php

Get certified by completing a course today!

Subscribe

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Your Suggestion:

Thank you for helping us.

Your message has been sent to W3Schools.

Top Tutorials

Top references, top examples, web certificates, get certified.

PHP: settype() function

Description.

The settype() function is used to set the type of a variable.

(PHP 4 and above)

Parameters:

*Mixed: Mixed indicates that a parameter may accept multiple (but not necessarily all) types.

Return value:

TRUE on success or FALSE on failure.

Value Type : Boolean.

View the example in the browser

Practice here online :

PHP Function Reference

Previous: serialize Next: strval

Follow us on Facebook and Twitter for latest update.

PHP: Tips of the Day

Groups the elements of an array based on the given function

To ensure you get the best browsing experience, this website is using cookies. By using our website, you agree to our use of cookies. More Info.

How to create a PHP string

A string is a series of characters. There are exactly 256 different characters possible. The present stable versions of PHP - PHP4 and PHP5 , have no native support for Unicode. There aren't string length limitations in PHP except the server's available memory and the configuration of the php.ini settings file.

Strings in PHP

Php strings and echo, php strings with single and double quotes, php strings with heredoc.

PHP strings and NTC Hosting

The string, like a variable , will have to be created first. There are two ways to use a string in PHP - you can store it in a function or in a variable. In the example below, we will create a string twice - the first time storing it in a variable, and the second time - in a function, in our case - an echo.

A sample string usage:

The output of this php file will be:.

In this example, the first string is stored in a variable, while the second one is not. If you store your strings, you will be able to use them later on, without the need to specify them once more.

Heredoc string usage:

In order to output a string you can use the PHP echo function. You can place either a string variable or you can use quotes to create a string that the echo function will output. You can output HTML using a PHP string. However, you must be careful when using HTML code or any other string that includes quotes. You can set a string in three different ways - using single quotes, using double quotes or using the heredoc method.

Like all values in PHP, strings too will have to stay in quotes when specified. There are two ways of quoting when you can specify a string in PHP - single quotes or double quotes. If you want to use a single quote within the string you have to escape the single quotes (otherwise known as apostrophes) with a backslash. If you choose to use double quotes, note that this method allows many special escape characters to be used unlike the case with the single-quote string. Once again, a backslash is used to escape a character. When a string is specified with single quotes, all variables in the string will not be treated as variables, but as text, and will not be passed to the output.

Differences in string quoting:

The two methods above are traditional for creating strings in most programming languages. PHP has introduced a more robust string creation tool called heredoc that lets the programmer create multi-line strings without using quotations. However, creating a string using heredoc is more difficult and can lead to problems if you do not properly code your string. In order to use heredoc, you need to open a string using <<< and some identifier, for example TEXT. Then you should type your text. To close the heredoc, repeat the identifier followed by a semicolon (TEXT;). Note that the closing sequence TEXT; must occur on a line by itself and cannot be indented.

A Heredoc PHP string

When a string is specified in double quotes or with heredoc, variables are parsed within it.

Escaped characters: *

Useful php string functions.

Besides the echo function, there are also several other functions you can use with PHP strings:

A sample usage of the strlen() function

A sample usage of the str_replace function:.

This will search for all instances of "red" in the string and replace them with "blue". The output of the above is:

A sample usage of the strtoupper() function

The above will output:

A sample usage of the ucfirst() function:

A sample usage of the trim() function:.

If you are a web developer or a webmaster and are using PHP for your projects, we, at NTC Hosting, will provide you with a complete solution. Our web hosting plans support both PHP4 and PHP5. You are not limited to choosing just one, but can change PHP versions all the time via our easy to use Web Hosting Control Panel .

With our PHP-optimized packages you can not only run all your PHP projects, but also extend them using a Perl - or a Python based script

© 2002 - 2023 {ntc}hosting.com. All Rights Reserved!

Related Articles

PHP | strval() Function

The strval() function is an inbuilt function in PHP and is used to convert any scalar value (string, integer, or double) to a string. We cannot use strval() on arrays or on object, if applied then this function only returns the type name of the value being converted.

Parameter : This function accepts a single parameter $variable . This parameter represents the value which we want to convert to string

Return value : This function returns a string. This string is generated by typecasting the value of the variable passed to it as a parameter.

Below programs illustrate the strval() function.

Program 1 :

Program 2 :

Program 3 :

Reference : http://php.net/manual/en/function.strval.php

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples .

Please Login to comment...

New Course Launch!

Improve your Coding Skills with Practice

Start your coding journey now.

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Converting an integer to a string in PHP

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

YanDatsiuk's user avatar

15 Answers 15

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.

IPSDSILVA's user avatar

There's many ways to do this.

Two examples:

See the PHP Manual on Types Juggling for more.

Sanjay Sheth's user avatar

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:

Another way is to encapsulate in quotes:

Peter Mortensen's user avatar

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:

You could also take advantage of PHP's implicit type conversion and string interpolation:

Finally, similar to the above, any function that accepts and returns a string could be used to convert and integer. Consider the following:

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.

Alana Storm's user avatar

Or it could be:

Your Common Sense's user avatar

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:

Microprocessor Cat's user avatar

There are many possible conversion ways:

UserBSS1's user avatar

You can either use the period operator and concatenate a string to it (and it will be type casted to a string):

Or, more correctly, you can just type cast the integer to a string:

Andrew Dunkman's user avatar

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.

troelskn's user avatar

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 :)

merkuro's user avatar

So the echo will be return string .

Kaushik shrimali's user avatar

My situation :

I'm working ...

temur Usmonaliyev's user avatar

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:

Dave's user avatar

You can simply use the following:

Elzo Valugi's user avatar

is faster than

Arthur Kushman's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged php string casting type-conversion integer or ask your own question .

Hot Network Questions

set string php

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

// Tutorial //

How to work with strings in php.

Default avatar

By alenaholligan

How To Work with Strings in PHP

The author selected Open Sourcing Mental Illness Ltd to receive a donation as part of the Write for DOnations program.

Introduction

A string is a sequence of one or more characters that may consist of letters, numbers, or symbols. All written communication is made up of strings. As such, they are fundamental to any programming language.

In this article, you will learn how to create and view the output of strings, how to use escape sequences, how to concatenate strings, how to store strings in variables, and the rules of using quotes, apostrophes, and newlines within strings in PHP.

Single and Double-Quoted Strings

You can create a string in PHP by enclosing a sequence of characters in either single or double quotes. PHP will actually interpret the following strings differently:

Before output, double-quoted strings will evaluate and parse any variables or escape sequences within the string. Single-quoted strings will output each character exactly as specified. The exception for single-quoted strings is a single quote (and backslash when needed).

If you were to echo this string in PHP:

It would return this output:

If you don’t include a backslash before the apostrophe in the single-quoted string, PHP will end the string at that point, which will cause an error. Since you’re using single quotes to create our string, you can include double quotes within it to be part of the final string that PHP outputs.

If you want to render the \' sequence, you must use three backslashes ( \\\' ). First \\ to render the backslash itself, and then \' to render the apostrophe. The sequence \" is rendered exactly as specified.

As with the single-quoted string, if a backslash is not included before the double quotes in the double-quoted string, PHP will end the string at that point, which will cause an error. Since the double-quoted string is not ended with a single quote, you add the apostrophe directly to a double-quoted string. A double-quoted string will output \' with either a single or double backslash used with the apostrophe.

To output the \" sequence, you must use three backslashes. First \\ to render the backslash itself, and then \" to render the double quote. The sequence \' is rendered exactly as specified.

The \ is known as an escape character. Combined with a secondary character, it makes up an escape sequence . Now that you have an understanding of strings, let’s review escape sequences.

Escape Sequences

An escape sequence tells the program to stop the normal operating procedure and evaluate the following characters differently.

In PHP, an escape sequence starts with a backslash \ . Escape sequences apply to double-quoted strings. A single-quoted string only uses the escape sequences for a single quote or a backslash.

Here are some common escape sequences for double-quoted strings:

Here is an example of how you can use these sequences in a string:

Using escape sequences gives us the ability to build any string required while including these special characters.

Creating and Viewing the Output of Strings

The most important feature of double-quoted strings is the fact that variable names will be expanded, giving you the value of the variable. You can use a variable to stand in for a string or use a string directly. You output the string by calling the echo function:

The $my_name variable is created on the first line. On the second line, the echo function is used to output a string in single quotes. Using the $my_name variable within this single-quoted string displays the characters exactly as they are written, so we will see the variable name instead of its value.

On the fourth line, we use the echo function again, but we are using double quotes this time. This time the variable is expanded to show the value in the first sentence. In the next sentence, there is a \ before the $ to explicitly tell the string to display a $ character and not expand the variable.

Note: When string evaluation is not a concern, you may choose to use either single quotes or double quotes, but whichever you decide on, you should be consistent within a program. Single quotes may be marginally faster .

With an understanding of how to create and view the output of strings, let’s move on to see how you can manipulate strings.

String Concatenation

Concatenation means joining strings together, end-to-end, to build a new string. In PHP, there are two main ways to concatenate a string.

The first is to include a string variable within a double-quoted string. This was shown in the previous step and in the following:

Running this code will combine the string and the $answer variable, which is set to Chews wisely. :

A second way to concatenate strings is to use the . operator.

Let’s combine the strings "Sammy" and "Shark" together with concatenation through an echo statement:

This code uses the . operator to combine the "Sammy" string and the "Shark" string without a space in between.

If you would like whitespace between the two strings, you must include the whitespace within a string, like after the word Sammy :

You cannot use concatenation to combine a string with an integer:

This will produce an error:

If you put "27" within quotes, it will evaluate as a string.

PHP is a loosely typed language , which means that it will try to convert the data it is given based on the request. If you set a variable to 27 , when used in concatenation with a string, PHP will parse the variable as a string:

You’ve covered the two main ways to concatenate, or combine, strings. Sometimes you may want to replace, or add to, the string completely. Next, let’s explore how PHP allows you to overwrite or update a string.

Updating a String

Normal variables in PHP are mutable , which means they can be changed or overwritten. Let’s explore what happens when you change the value for the $my_name variable:

First, the variable was set to "Sammy" and displayed using echo . Then it was set to "Shark" , overwriting the variable, so that when echo was called a second time, it displayed the new value of "Shark" .

Instead of overwriting the variable, you can use the concatenating assignment operator .= to append to the end of a string:

First, you set the $my_name variable to "Sammy" , then used the .= operator to add " Shark" to the end of it. The new value for $my_name is Sammy Shark .

To prepend to the beginning of a string, you would overwrite while using the original string:

This time, you first set the $my_name variable to "Shark" , then used the = operator to override the $my_name variable with the new string "Sammy " , combined with the previous value of the $my_name variable, which before being overridden is "Shark" . The final value for $my_name is Sammy Shark .

Overwriting, appending, and prepending give us the ability to make changes and build the strings required for our applications.

Whitespace in Strings

Because PHP does not care about whitespace, you can put as many spaces or line breaks within your quotes as you would like.

Keep in mind that HTML renders whitespace differently. New lines require a <br> tag, so even though your source may have new lines, you will not see those new lines displayed on a web page. Similarly, no matter how many spaces there are in your code, only a single space is displayed between characters.

Clean and consistent use of whitespace is one of the best tools for making code more readable. Since PHP essentially ignores whitespace, you have a lot of flexibility that you can use to your advantage. An integrated development environment (IDE) can help you stay consistent with your code and use of whitespace.

Being able to control the way our strings are rendered is essential for communicating with an application’s end user. By updating and combining variables that include special characters, you can clearly communicate while keeping repetition to a minimum.

As you continue to work with strings, keep in mind these three aspects:

If you would like to read more about PHP, check out the PHP topic page .

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us

Tutorial Series: How To Code in PHP

PHP banner image

PHP is a popular server scripting language known for creating dynamic and interactive web pages.

Still looking for an answer?

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Creative Commons

Popular Topics

Try DigitalOcean for free

Join the tech talk.

Please complete your information!

How to Convert an Integer to a String in PHP

Topic: PHP / MySQL Prev | Next

Answer: Use the strval() Function

You can simply use type casting or the strval() function to convert an integer to a string in PHP.

Let's take a look at an example to understand how it basically works:

Related FAQ

Here are some more FAQ related to this topic:

Bootstrap UI Design Templates

Is this website helpful to you? Please give us a like , or share your feedback to help us improve . Connect with us on Facebook and Twitter for the latest updates.

Interactive Tools

BMC

IMAGES

  1. How to Count a specified characters in a string in PHP

    set string php

  2. Sort string PHP

    set string php

  3. String in PHP

    set string php

  4. String Functions in PHP: Part 13

    set string php

  5. How to return int and string in PHP Json API output?

    set string php

  6. PHP Strings: PHP String Functions Explained with Examples

    set string php

VIDEO

  1. Strings in PHP

  2. Tennis set string machine BOLT

  3. PHP String Part 2

  4. php & MySql

  5. php://input

  6. PART 16. PHP String Operators

COMMENTS

  1. settype

    Using settype is not the best way to convert a string into an integer, ... next time you set the value of that variable php will change its type as well.

  2. Strings

    The simplest way to specify a string is to enclose it in single quotes (the character ' ). To specify a literal single quote, escape it with a backslash ( \ ).

  3. String Operators

    The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment

  4. PHP settype() Function

    The settype() function converts a variable to a specific type. Syntax. settype(variable, type);. Parameter Values. Parameter, Description. variable

  5. PHP settype() function

    The settype() function is used to set the type of a variable. Version: (PHP 4 and above). Syntax: settype(var_name, var_type). Parameters: Name

  6. How easy is it to create a PHP string?

    In order to output a string you can use the PHP echo function. You can place either a string variable or you can use quotes to create a string that the echo

  7. PHP

    The strval() function is an inbuilt function in PHP and is used to convert any scalar value (string, integer, or double) to a string.

  8. Converting 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

  9. How To Work with Strings in PHP

    You can create a string in PHP by enclosing a sequence of characters in either single or double quotes. PHP will actually interpret the

  10. How to Convert an Integer to a String in PHP

    You can simply use type casting or the strval() function to convert an integer to a string in PHP. Let's take a look at an example to understand how it