3

How to convert a string format into an array format?

I have a string, $string = 'abcde'

I want to convert it to a 1 element array

$string[0] = 'abcde'

Is there a built in function for this task? Or the shortest way is to

$string = 'abcde';
$array[0] = $string;
$string = $array;

TIA

3
  • What do you mean by string "format" and array "format"? What are you trying to accomplish? Commented Jun 1, 2010 at 20:37
  • I think you need to update your tags to describe what programming language you're using. Commented Jun 1, 2010 at 20:39
  • Sorry, it is in php What I am trying to do is that I have a variable name that I am using to store a return value from a function, the value can either be a string or an array. I don't want to run an "if (is_array($string))" statement later on to check. Commented Jun 1, 2010 at 20:50

2 Answers 2

3

All kinds of ways in php..

$array = array('abcde');

$array[] = 'abcde';

Etc... not too sure what you're going for.

Edit: Oh, I think you might want to convert the first variable? Like this?

//Define the string
$myString = 'abcde';

//Convert the same variable to an array
$myString = array($myString);

Edit 2: Ahh, your comment above I think clears it up a little. You're getting back either an array or a string and don't know which. If you do what I just said above, you might get an array inside an array and you don't want that. So cast instead:

$someReturnValue = "a string";
$someReturnValue = (array)$someReturnValue;
print_r($someReturnValue);

//returns
Array
(
    [0] => a string
)


$someReturnValue = array("a string inside an array");
$someReturnValue = (array)$someReturnValue;
print_r($someReturnValue);

//returns
Array
(
    [0] => a string inside an array
)
Sign up to request clarification or add additional context in comments.

2 Comments

You could use the (array) cast. Going to edit the answer to show you.
Great, I will keep the second part of your answer in mind. The first part actually saved me a bunch of if condition codes.
0

Lets not forget the standard way of declaring a string as an array in PHP, before adding elements..

$string = array();

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.