Seems like it works, but better to catch it before it even gets into the array, could use a small function or a getter setter.
Fun with Maps! 🗺
Hello!
Code:
$arr = [1, 2, 3, 6, "7"];
function upwardTrend($arr) {
return array_map(function($item){
if(is_string($item)) {
return "Strings not permitted!";
}
return $item;
}, $arr);
}
print_r(upwardTrend($arr));
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 6
[4] => Strings not permitted!
)
I wanted to ask if this is "the best way" to check an array, for example, to see if it might contain strings where there should only be numbers.
In the past I used imm "foreach", but now I try to use "array_map" more often.
Is this a good style?
Thanks! ✨
Array's have so many use cases, you could even use array_filter to filter out non numeric values.
I usually like looping an array rather than a mix of json and array (json array). Example: https://gist.github.com/jimgwhit/cbbe5bb0d2556fdc7e37a86d3630239c
But there are many array methods, I like how you mapped above.
Edit: was on phone earlier:
Example:
$arr = [1, 2, 3, 6, "Hello World", 12, null];
$array = array_filter($arr, 'is_numeric');
dd($array);
Gives:
array:5 [▼
0 => 1
1 => 2
2 => 3
3 => 6
5 => 12
]
I use map when there isn't another straight forward method, like:
$data = DB::table('dc_dogs')->where('adopted', '=', 0)->get();
$dogs = collect($data)->map(function($x){ return (array)$x; })->toArray();
See https://laracasts.com/discuss/channels/guides/to-array
Of course if I can directly query data from db, I do.
Please or to participate in this conversation.