Reputation: 1519
I am working on a php code as shown below in which the values (let us supposed I entered 12, 13, 14) of $data->{"articles_id_" . ICL_LANGUAGE_CODE}
is coming through admin portal.
Let us suppose I have entered 12, 13, 14 for "articles_id_" . ICL_LANGUAGE_CODE
Php code:
'post__in' => array($data->{"articles_id_" . ICL_LANGUAGE_CODE}),
On debug it is returning:
[post__in] => Array
(
[0] => 12, 13, 14
)
Whereas I want to be returned like this:
[post__in] => Array
(
[0] => 12
[1] => 13
[2] => 14
)
Problem Statement:
I am wondering what changes I should make in the php code above so that its return in the way I want.
Upvotes: 0
Views: 75
Reputation: 21671
You can use this too:
'post__in' => str_getcsv($data->{"articles_id_" . ICL_LANGUAGE_CODE}),
str_getcsv — Parse a CSV string into an array
str_getcsv( string $input,string $delimiter=",",string $enclosure='"',string $escape="\" ) :array
Then if it has ,\s
you can trim using array map.
'post__in' => array_map('trim', str_getcsv($data->{"articles_id_" . ICL_LANGUAGE_CODE})),
In this case it's similar to explode
or preg_split
, but those were taken already as answers ... :-p
This treats it more like a CSV line so it will deal with things like this foo,"Some other thing",bar
- Some CSV formats (includng PHP fputcsv
and SplFileObject::fputcsv
will enclose strings with spaces or commas with double quotes "
. Explode/Preg Split would retain the "
but this would remove them. It also does a few other things that are CSV related. But as I said, in this case with integers it's basically the same as explode(',', ...)
Cheers!
Upvotes: 1
Reputation: 23958
Explode or preg_split.
Explode is static and must have both comma and space.
'post__in' => explode(", ",$data->{"articles_id_" . ICL_LANGUAGE_CODE}),
Preg_split can have an optional space, meaning it can split strings like "12,13,14"
and "12, 13, 14"
and even "12, 13, 14"
which explode can't.
'post__in' => preg_split("/,\s*/",$data->{"articles_id_" . ICL_LANGUAGE_CODE}),
If it's user input you need to split then I would definitely go for preg_split.
It's very common for "normal" people (not programmers) to write numbers with space in-between.
Upvotes: 3
Reputation: 17289
'post__in' => explode(',', $data->{"articles_id_" . ICL_LANGUAGE_CODE}),
Upvotes: 1
Reputation: 21465
If the value of $data->{"articles_id_" . ICL_LANGUAGE_CODE}
is a comma-separated string, you should explode()
it:
'post__in' => explode(",", $data->{"articles_id_" . ICL_LANGUAGE_CODE})
Upvotes: 2