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

Link to comment
Share on other sites

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


Link to comment
Share on other sites

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
Edited by matthewtbaker
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.