Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP How to add backslash inside array of strings?
To add backslashes inside an array of strings, you can use json_encode() function twice. This technique is useful when you need to escape quotes within JSON strings for JavaScript or database storage.
Let's say the following is our array −
$value = [
"ADD", "REMOVE", "SELECT", "MODIFY"
];
We want the output with backslashes inside array of strings i.e −
"["ADD","REMOVE","SELECT","MODIFY"]"
Using Double json_encode()
The PHP code is as follows −
<?php
$value = [
"ADD", "REMOVE", "SELECT", "MODIFY"
];
echo json_encode(json_encode($value)) . "<br>";
?>
This will produce the following output −
"["ADD","REMOVE","SELECT","MODIFY"]"
How It Works
The first json_encode() converts the PHP array to JSON format. The second json_encode() escapes the quotes and wraps the entire string in quotes, adding the necessary backslashes before internal quotes.
Alternative Method Using addslashes()
You can also achieve similar results using addslashes() function −
<?php
$value = [
"ADD", "REMOVE", "SELECT", "MODIFY"
];
$jsonString = json_encode($value);
echo '"' . addslashes($jsonString) . '"';
?>
"["ADD","REMOVE","SELECT","MODIFY"]"
Conclusion
Double json_encode() is the most efficient method to add backslashes inside array strings. This technique is particularly useful when preparing data for JavaScript or escaping JSON strings for database storage.
