A seemingly elegant shortcut
You have a string called myString that contains IDs, delimited with commas: 103,412, 422,781.
Now you would like to do something with each of the IDs inside an Apply to each loop. In theory it sounds like a very efficient idea to use the following expression to create an array right where you need it - in the input variable field of "Apply to each":
split(variables('myString'),',')
The caveat
What if the string is empty (aka null)? The function split will fail, because it expects a text as its first argument.
The solution: try and make sure that myString is at least an empty string, using coalesce:
split(coalesce(variables('myString'),''),',')
Another caveat
The flow is still failing (sometimes), what the hell! The issue here is that you are now splitting an empty string into an array. And the output of this isn't simply an empty array, but an array of size 1, where the value of the first element is an empty string.
[""]
So your "Apply to each" loop runs 1 time even though it was supposed to run 0 times😡.
[""]
So your "Apply to each" loop runs 1 time even though it was supposed to run 0 times😡.
In an ideal world, the following expression would return an empty array - so it can be used for "Apply to each":
split(null, ',')
Sadly, it doesn't.
What we need to do is to explicitely create an empty array, using json('[]'), should the input string be null:
if(empty(variables('myString')), json('[]'), split(variables('myString'), ','))