lgt
lgt

Reputation: 1034

php's explode array index

Using php's explode with the following code

$data="test_1, test_2, test_3";
$temp= explode(",",$data);

I get an array like this

array('0'=>'test_1', '1'=>'test_2', 2='test_3')

what I would like to have after explode

array('1'=>'test_1', '2'=>'test_2', 3='test_3')

Upvotes: 0

Views: 1390

Answers (6)

mickmackusa
mickmackusa

Reputation: 48001

Lloyd Watkin's answer makes the fewest function calls to achieve the expected result. It is certainly a superior answer to ManseUK's method which uses four functions in its one-liner after the string has been exploded.

Since this question is nearly 5 years, old there should be something valuable to add if anyone dare to chime in now...

I have two things to address:

  1. The OP and Lloyd Watkins both fail to assign the correct delimiter to their explode method based on the sample string. The delimiter should be a comma followed by a space.

    Sample Input:

    $data="test_1, test_2, test_3";
    
  2. No one has offered a one-liner solution that matches Lloyd's two-function approach. Here that is: (Demo)

    $temp=array_slice(explode(", ",", $data"),1,null,true);
    

    This two-function one-liner prepends the $data string with a comma then a space before exploding it. Then array_slice ignores the first empty element, and returns from the second element (1) to the end (null) while preserving the keys (true).

    Output as desired:

    array(
        1 => 'test_1',
        2 => 'test_2',
        3 => 'test_3',
    )
    

Upvotes: 0

Lloyd Watkin
Lloyd Watkin

Reputation: 505

You couldn't do it directly, but this will do what you're after:

$temp=explode(',',',' . $data);
unset($temp[0]);
var_dump($temp);
array(3) {
  [1]=>
  string(6) "test_1"
  [2]=>
  string(7) " test_2"
  [3]=>
  string(7) " test_3"
}

Upvotes: 0

Ozerich
Ozerich

Reputation: 2000

it is impossible using explode.

for($i = count($temp) - 1; $i >= 0; $i--) 
    $temp[$i + 1] = $temp[$i];
unset($temp[0]);

Upvotes: 0

Manse
Manse

Reputation: 38147

You could something like this :

$temp = array_combine(range(1, count($temp)), array_values($temp));

uses array_combine() to create array using your existing values (using array_values()) and range() to create a new range from 1 to the size of your array

Working example here

Upvotes: 2

Tim Withers
Tim Withers

Reputation: 12059

You could use this possibly (untested)

$newArray=array_unshift($temp,' ');
unset($newArray[0]);

Upvotes: 0

Fluffeh
Fluffeh

Reputation: 33542

Array indexes start at 0. If you really wanted to have the array start with one, you could explode it, then copy it to another array with your indexes defined as starting at 1 - but why?

Upvotes: 1

Related Questions