0

My variable like this,

$a = "A1|A2|A3|";

so how to convert php array?

to this,

$a=array("A1","A2","A3");
asked Aug 21, 2014 at 7:12
1
  • 7
    $a = explode('|', $a); It's one of the functions most people learn before anything else Commented Aug 21, 2014 at 7:13

6 Answers 6

4

First, trim off the pipe at the end of your input.

$str = rtrim($a, '|');

Then, explode on the pipe.

$a = explode('|', $str);

Alternatively, do the split normally and then filter out the whitespace entries as a post-processing step.

$a = array_filter($a, 'strlen');
answered Aug 21, 2014 at 7:14
Sign up to request clarification or add additional context in comments.

1 Comment

+1 Only correct answer on this question. Without trimming last pipe, you will get empty element in array. I don't understand how other answers has got upvote.
3

Use explode function.

$a = rtrim("|", $a);
$a = explode('|', $a);
print_r($a);
Satish Sharma
9,6356 gold badges32 silver badges52 bronze badges
answered Aug 21, 2014 at 7:14

1 Comment

check @alex answer. You need to trim the last | or else you will get last empty element in array.
1

You can do achieve what you want to this way:

$a = "A1|A2|A3|"; 
$a = rtrim($a, '|'); // Trimming the final |
$exploded = explode("|", $a); // Extracting the values from string.
var_dump($exploded);

Hope it answers your question. Refer rtrim and explode on official documentation site for more relevant details.

Emmanuel
14.2k12 gold badges53 silver badges73 bronze badges
answered Aug 21, 2014 at 7:17

1 Comment

+1 for trimming the last pipe and mentioning comments as well in answer.
0
$a = "A1|A2|A3|";
$newA = explode("|",$a);
print_r($newA);
answered Aug 21, 2014 at 7:15

1 Comment

check @alex answer. You need to trim the last | or else you will get last empty element in array.
0
$a = "A1|A2|A3|";
print_r(array_filter(explode("|", $a)));
answered Jan 9, 2015 at 11:14

Comments

0
$a=explode('|',$a);

Check this link

explode

explode — Split a string by string

Description: array explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] )

answered Aug 21, 2014 at 7:14

1 Comment

check @alex answer. You need to trim the last | or else you will get last empty element in array.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.