Jump to content

Split String And Create Array With Named Values


matthewtbaker

Recommended Posts

Hi,

 

I've been searching high and low for this answer all day and still no luck, so I thought I'd reach out to a fellow PHPer. If you can help I'd be most grateful!

Ok here's the problem I'm trying to solve:

 

 

I have a string value of;

 

 

show_title=yes,show_intro=no,show_category=yes,show_print_icon=no,show_email_icon=yes

 

 

I would like to split the string value in two places (removing the symbol at the same time), at the comma and at the equals. Then I'd like to put the values into an array naming each entry by the value entered before the equals symbol. Like so,

 

 

show_title => yes

show_intro => no

show_category => yes

show_print => no

show_email_icon => no

 

 

I'm hoping from doing this I can then easily refer to the setting I need later in my script.

 

if ($array[show_print] == true) {

you get the idea...

}

 

 

Thank for your time again!

 

Matt

Probably the easiest thing to do would be str_replace the commas with ampersands, then use parse_str with the optional second parameter to parse it into an associative array.

<?php
$str = "show_title=yes,show_intro=no,show_category=yes,show_print_icon=no,show_email_icon=yes";
$str = str_replace(',', "\n", $str);
$x = parse_ini_string($str);
echo '<pre>'.print_r($x, 1).'</pre>';
?>

Result:

Array
(
   [show_title] => 1
   [show_intro] =>
   [show_category] => 1
   [show_print_icon] =>
   [show_email_icon] => 1
)


  On 10/2/2012 at 3:16 PM, Pikachu2000 said:

Probably the easiest thing to do would be str_replace the commas with ampersands, then use parse_str with the optional second parameter to parse it into an associative array.

 

Thank you for the speedy reply Pikachu2000! It tried this approach and works like a charm.

 

For those coming across this, the solution looked like the below.

 

 

$strAttributesNew
=
str_replace
(
"
,
"
,
"
&
",
$strAttributes
)
;

parse_str
(
$strAttributesNew
,
$myNewArray
)
;

 

print_r
(
$myNewArray
)
;
//just to check all is working ok

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.