Connecting Tech Pros Worldwide Forums | Help | Site Map

How to turn a string into an array

Member
 
Join Date: Jan 2007
Posts: 47
#1: Jul 7 '08
Hi,

I would like to turn a hidden field value which I receive from an HTML page into an array. It would just be that something like:

[PHP]$layer = "boundaries"[/PHP]

should become:

[PHP]$layer[0] = "boundaries"[/PHP]

But if I use this:

[PHP] if (!is_array($layer))
{
$layer[0] = $layer;
}[/PHP]

it seems that PHP doesn't consider that $layer has been turned in array. Using the (!is_array) verification just after this, shows that $layer is still not considered as array...

What can/should I do? Thanks for any hints!

Needs Regular Fix
 
Join Date: Mar 2008
Posts: 311
#2: Jul 7 '08

re: How to turn a string into an array


Expand|Select|Wrap|Line Numbers
  1. if (!is_array($layer))
  2. {
  3.     $tmp = $layer;
  4.     $layer = array();
  5.     $layer[0] = $tmp;
  6. }
  7.  
I would do it this way. I don't know what PHP would do if you tried to redeclare $layer as an array and at the same time initialize its first and only member to the value stored as $layer. So better to break it up and use a variable like $tmp to store the original $layer value.
Member
 
Join Date: Jan 2007
Posts: 47
#3: Jul 7 '08

re: How to turn a string into an array


Quote:

Originally Posted by coolsti

Expand|Select|Wrap|Line Numbers
  1. if (!is_array($layer))
  2. {
  3.     $tmp = $layer;
  4.     $layer = array();
  5.     $layer[0] = $tmp;
  6. }
  7.  

Great. Thanks a lot!
pbmods's Avatar
Site Moderator
 
Join Date: Apr 2007
Location: Texas
Posts: 5,435
#4: Jul 7 '08

re: How to turn a string into an array


You can also do this:

Expand|Select|Wrap|Line Numbers
  1. $layer = array($layer);
  2.  
Since $layer is a string, when you say $layer[0], you are referencing the first character of $layer rather than converting it to an array.

This will also work:
Expand|Select|Wrap|Line Numbers
  1. http://www.example.com/path/to/script.php?layer[]=boundaries
  2.  
Reply