Page 1 of 1

PHP Array

Posted: Fri Mar 10, 2006 5:30 pm
by quadoc
I've the following string $st = "1,5,3,2" and I want to put the value into an array $a like
a[1] = "1"
a[2] = "5"
a[3] = "3"
a[4] = "2"

How do I do that? Could someone posts some tips. Thanks...

Posted: Fri Mar 10, 2006 5:33 pm
by Benjamin

Code: Select all

$VariableName = array(
  '1' => 'String Text',
  '2' => 'String Text',
  '3' => 'String Text',
  '4' => 'String Text',
  '5' => 'String Text'
);
EDIT: Oh I just reread your question. You will want to use the explode() function.

Posted: Fri Mar 10, 2006 5:34 pm
by quadoc
I'm sorry, I want to do it using php code. Thanks...

Posted: Fri Mar 10, 2006 5:35 pm
by feyd

Posted: Fri Mar 10, 2006 5:50 pm
by quadoc
How do I explode the string with index starting with 1 not 0?

Posted: Fri Mar 10, 2006 5:54 pm
by feyd
You don't. Arrays count from zero. What do you need it to start from one for?

Posted: Fri Mar 10, 2006 5:58 pm
by quadoc
But is there a way to start index from 1? Thanks...

Posted: Fri Mar 10, 2006 6:11 pm
by John Cartwright
Reguardless when using an array, it will be indexed starting at 0.

Posted: Fri Mar 10, 2006 10:35 pm
by feyd
the only way is basically brute forcing it, by either creating the array yourself or putting something into the zero slot when the array is initially created then removing it.

Tell us what you actually want to do with it, maybe there's another more simple solution.

Re: PHP Array

Posted: Sat Mar 11, 2006 4:04 am
by NightFox
quadoc wrote:I've the following string $st = "1,5,3,2" and I want to put the value into an array $a like
a[1] = "1"
a[2] = "5"
a[3] = "3"
a[4] = "2"

How do I do that? Could someone posts some tips. Thanks...
If you really want to start it at 1 instead of zero, just add a comma to the beginning of your list like this:

Code: Select all

$st = "1,5,3,2"; // your original
$st = ",1,5,3,2"; // added extra comma
$a = explode(",",$st);
unset($a[0]);
But this is completely pointless when you can just have your code start with zero instead of 1.

just a little fyi, in case you didn't know. :)

Code: Select all

$bob[] = "hello"; // saves to $bob[0]
$bob[] = "yellow"; // saves to $bob[1] and so on...