0

I have string like this 1-male,2-female I want to make this as array like following

array(
    1 => male,
    2 => female
);

i can make this by using foreach Ex:

$str1 = '1-male,2-female';
$outPutArr = array();
$arr1 = explode(',' $str1);
foreach($arr1 as $str2){
    $arr2 = explode('-', $str2);
    $outPutArr[$arr2[0]] = $arr2[1];
}

Is there any other short cut to do this?

3
  • 1
    No... nothing wrong with what you did... Commented Jul 15, 2013 at 20:23
  • @Neal stackoverflow.com/questions/8509040/… See this Post. I want some thing like this. Commented Jul 15, 2013 at 20:24
  • @rkaartikeyan this loses the values of the keys. Commented Jul 15, 2013 at 20:36

2 Answers 2

7

You can use a simple regex and preg_match_all to simplify it down to:

preg_match_all('/(\d+)-([^,]+)/', $input, $matches);
$array = array_combine($matches[1], $matches[2]);

array_combine mixes it back to:

Array
(
    [1] => male
    [2] => female
)

Another common approach is utilizing parse_str() after strtr() to replace whatever delimiters your string has into = and &.

Sign up to request clarification or add additional context in comments.

2 Comments

Hai Bro thanks for your Answer. But What is Input? and Matches? What i have to put there?
$input is your $str1, while $matches is a result variable and by-product that you don't have to provide.
1

This should probably work, although I didn't test it. It's just another way of doing it to give you more options:

$String = "1-male,2-female";
$Array = array();
foreach (array_chunk(explode(array('-', ','), $String), 2) as $Ar)
  $Array[$Ar[0]] = $Ar[1];

How it works:

It splits the data into an array of this form:

array('1', 'male', '2', 'female')

That's what the explode is for. Then it rearranges it into chunks of 2 like this:

array(array('1', 'male'), array('2', 'female'))

Last, in a foreach, it merges each array into it's first element (key) and second element (value).

array('1' => 'male', '2' => 'female')

Note that, if an array key is repeated, the value is overwritten.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.