Reputation: 13843
I have an comma seperated list of values held as a string:
blue, left-right-middle, panther.png
I then have three functions:
Sets background colour
Sets order of columns for layout
Sets a profile image
At the moment I use a for each
loop to explode the values into seperate strings, but how can I better control the results.
E.g
First result of array = Sets background colour
Second result of array = Sets order of columns
Third results of array = profile image
Can I write the results of the array to 3 seperate variables in anyway, so I can assign the variable to each function?
Like so:
First result of array = $backgroundColour
Second result of array = $orderColumns
Third results of array = $profileImage
Any ideas how I might go about this?
Upvotes: 2
Views: 196
Reputation: 42140
Just to be different, you could use sscanf
$string = 'blue, left-right-middle, panther.png';
sscanf( $string, '%s, %s, %s', $backgroundColour, $orderColumns, $profileImage );
Upvotes: -1
Reputation: 5335
Use this following code.
$string = 'blue, left-right-middle, panther.png';
list($color, $position, $image) = split (', ',$string);
echo 'Background color: ' . $color ."
\n";
echo 'Column order: ' . $postion. "
\n";
echo 'Profile image: ' . $image . "
\n"
Upvotes: 0
Reputation: 316969
As of PHP5.3 You could use str_getcsv()
to parse a CSV string into an array.
Also, have a look at list
to assign variables as if they were an array.
list( $color, $order, $image ) = str_getcsv($csvString);
Prior to PHP5.3, you'd use explode
instead of str_getcsv
. See example by @poke below.
The advantage of str_getcsv
over explode
is that you can specify delimiter, enclosure and escape character to give you more control over the result.
str_getcsv
is smart enough to trim whitespace automatically. The listed values would contain
string(4) "blue", string(17) "left-right-middle", string(11) "panther.png"`
However, added control does cost speed. explode
is substantially (~6 to 8 times on my machine) faster for the given example string.
Upvotes: 5
Reputation: 612
May you use the str_getcsv function of php.
See in manual: http://www.php.net/manual/en/function.str-getcsv.php
Upvotes: 0
Reputation: 3021
$array = explode(', ', 'blue, left-right-middle, panther.png');
list($color, $position, $image) = $array;
echo $color; // blue
echo $position; //left-right-middle
echo $image; //panther.png
Upvotes: 0
Reputation: 10340
You could make use of explode and list:
$string = 'blue, left-right-middle, panther.png';
list($backgroundColour, $orderColumns, $profileImage) = explode(', ', $string);
Upvotes: 1
Reputation: 387587
Use list
:
$line = 'blue, left-right-middle, panther.png';
list( $bkgColor, $columnOrder, $profileImage ) = explode( ', ', $line );
echo 'Background color: ' . $bkgColor . "<br />\n";
echo 'Column order: ' . $columnOrder. "<br />\n";
echo 'Profile image: ' . $profileImage . "<br />\n";
Upvotes: 4