I have a string comma separated where I want to get 2 values in variables. How can I accomplish it.
$responseData = "Data: invoice=1216,card=AMEX";
I am looking for value of Invoice and Card.
I tried using instring but not getting value I want.
You can use sscanf()
to achieve this result.
sscanf()
takes the same format as printf()
, allowing you to provide a variable and expected format string, and will return the matching results.
list($invoice, $card) = sscanf($responseData, "Data: invoice=%d,card=%s");
var_dump($invoice); // int(1216)
var_dump($card); // string(4) "AMEX"
Community wiki of Mark Baker's answer in the comments above.
You can also do this manually by breaking up the string by delimiters with explode()
. The Data:
component is irrelevant, so trim it off, then split by commas, then split by =
to get a key => value pair.
// Remove the Data: component
$responseData = ltrim($responseData, 'Data: ');
$example = array();
// Split by commas
foreach (explode(',', $responseData) as $value) {
// Split by equals
list ($k, $v) = explode('=', $value);
$example[$k] = $v;
}
var_dump($example);
// array(2) {
// ["invoice"]=>
// string(4) "1216"
// ["card"]=>
// string(4) "AMEX"
// }