5

I have code like bellow

$string = "Trainee,Beginner";

I want to replace the $string to array object with explode

$list = explode(',', $string);

The result I got.

array:2 [▼
  0 => "Trainee"
  1 => "Beginner"
];

The result I want.

array:2 [▼
  'Trainee' => "Trainee"
  'Beginner' => "Beginner"
];
5
  • 1
    Explain your output little bit more.Its confusing/misleading. Commented Apr 23, 2019 at 4:11
  • 3
    what do you mean by "i want between key and val equal" ? Commented Apr 23, 2019 at 4:12
  • 2
    Add your expected output to your question. Commented Apr 23, 2019 at 4:16
  • 1
    not clear ,pls edit Commented Apr 23, 2019 at 4:17
  • 1
    i'm sorry my english is not good, i just want to replace array object key same with array value. but the issue has been clear. @Always Sunny very helpful Commented Apr 23, 2019 at 11:05

3 Answers 3

5

You can do it with array_combine() that takes one array as key and another as value. So just pass the $list for both parameters and you're good to go.

<?php
$string = "Trainee,Beginner";
$list = explode(',', $string);
$final_array = array_combine($list, $list);
print_r($final_array);
?>

DEMO: https://3v4l.org/vmgaH

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

Comments

0

You can try using foreach loop

<?php
$string = "Trainee,Beginner";

$list = explode(',', $string);


foreach($list as $item){
    echo $item.'<br>';
}  

Output:

Trainee
Beginner

1 Comment

i do not want to looping, i just want the output like this array:2 [▼ 'Trainee' => "Trainee" 'Beginner' => "Beginner" ];
0

With Laravel you could just use the collect method.

$list = collect(explode(',', $string))->keyBy(function ($item) { return $item; });

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.