How can I use parse_str() function in PHP
0 2371
The main use of Parse string is that you don't need to make variables, it automatically defines variables from the string. This is an in built function, so you don't need to define this function in your function file.
Basically parse_str() function is used to get parameters from the URL.
There are two types of parameters passed in this function.
parse_str(string,array)
1. string= This is mandatory parameter. Here the string is defined.
2. array= This is an optional parameter and just only used to specifies the name of array in which variables will be stored.
For more clarification let's check some examples here:-
<?php $string = 'state=Delhi&state_code=07'; parse_str($string); echo 'State code of '.$state.' is '.$state_code; ?>
Output:
State code of Delhi is 07.
You can also use parse_str() direct without defining a variable.
For example:
<?php parse_str('order_id=CD093&product=shirt&amount=700'); echo 'Order Id of product ('.$product.') is '.$order_id; echo '<br>'; echo 'Payable amount is '.$amount; ?>
Output:
Order Id of product (shirt) is CD093
Payable amount is 700
If you wanna get as an array then can use like:-
<?php parse_str('order_id=CD093&product=shirt&amount=07',$set_array); print_r($set_array); ?>
Output:
Array ([order_id] => CD093 [product] => shirt [amount] => 07)
Also you can use by both types:- as an array and individually parameter of string.
<?php $string = 'order_id=OD091&brand=Pepe&product=Jeans&amount=2000'; parse_str($string,$set_array); print_r($set_array); echo '<br>'; echo 'Brand is '.$set_array['brand']; ?>
Output:
Array ([order_id] => OD091 [brand] => Pepe [product] => Jeans [amount] => 2000)
Brand is Pepe
Share:
Comments
Waiting for your comments