Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

loops

php

I have the following values:

$attached_products = "1,4,3";

I want to make an array that looks like:

$selected = array(1, 4, 3);

using a loop with my $attached_products.

like image 535
Emkey Avatar asked Jul 07 '26 00:07

Emkey


2 Answers

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)
like image 189
Jeremy Avatar answered Jul 08 '26 16:07

Jeremy


You use explode() for that:

$selected = explode(", ", $attached_products);
like image 44
Rolando Cruz Avatar answered Jul 08 '26 16:07

Rolando Cruz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!