开发者

How to make an array from a string using a loop?

开发者 https://www.devze.com 2023-04-04 12:25 出处:网络
I have the following values: $attached_products = \"1,4,3\"; I want to make an array that looks like: $selected = ar开发者_StackOverflow中文版ray(1, 4, 3);

I have the following values:

$attached_products = "1,4,3";

I want to make an array that looks like:

$selected = ar开发者_StackOverflow中文版ray(1, 4, 3);

using a loop with my $attached_products.


This could be done with a loop, but there's a simpler way.

You can break your string up around the commas using the explode function[php docs]. This will give you an array of strings of digits. You can convert each string to an integer by applying intval[php docs] using array_map[php docs].

$attached_products = "1,4,3";
$selected_strings = explode(',', $attached_products); # == array('1', '4', '3')
$selected = array_map('intval', $selected_strings);   # == array(1, 4, 3)


You use explode() for that:

$selected = explode(", ", $attached_products);


If there may or may not be whitespace after the comma, you could use preg_split().

$selected = preg_split(/,\s*/, $attached_products);

Alternatively you could use explode(), trim() and array_map().

$selected = array_map('trim', explode(',', $attached_products));

If they must be integers, map them through intval().

0

精彩评论

暂无评论...
验证码 换一张
取 消