Konstruktionsplan's avatar

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! ✨

0 likes
3 replies
jlrdw's avatar

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.

2 likes
Konstruktionsplan's avatar

Hey @jlrdw

$arr = [1, 2, 3, 6, "Hello World", 12, null];
function upwardTrend($arr) {
  $trash = [];
  $items = [];
	 array_map(function($item) use (&$trash, &$items) {
    	if(!is_integer($item)) {
          	$trash[] = $item;
        	return "Is in Trash";
        }
       return $items[] = $item;
    }, array_filter($arr));
  
  return [
    'Numbers' => $items,
    'Trash' => $trash
  ];
}

print_r(upwardTrend($arr));
Array
(
    [Numbers] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 6
            [4] => 12
        )

    [Trash] => Array
        (
            [0] => Hello World
        )

)

Like so? No zero values and the wrong values are stored in a separate array.

Would you do that in the big wide world? 🌏

jlrdw's avatar
jlrdw
Best Answer
Level 75

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.

2 likes

Please or to participate in this conversation.