Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace Array key in explode

Tags:

php

laravel

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"
];
like image 733
Muhammad Fauzi Avatar asked Apr 23 '19 04:04

Muhammad Fauzi


1 Answers

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

like image 126
Always Sunny Avatar answered Oct 11 '22 16:10

Always Sunny