Alois
Alois

Reputation: 11

Defining arrays by a loop in php

I have data in many arrays

$verbs_L1_occurr, 
$verbs_L2_occurr, 
$verbs_L3_occurr, 
.....)

and based on them I define new arrays removing all double values:

$verbs_L1_unique = array_unique($verbs_L1_occurr);  
$verbs_L2_unique = array_unique($verbs_L2_occurr);
$verbs_L3_unique = array_unique($verbs_L3_occurr);
etc.

My whole code including this snippet works perfectly fine and being a beginner I am insanely proud of it, but I find it disturbing to have so many repeating lines. I suspect any experienced programmer would have a good laugh here...

Question therefore: how can I simplify this? Whichever way I tried to loop through this, I don't get it right. Tried a counter to loop through, but whatever I do I get an error or 'invalid argument'. Am very grateful for any hint, thank you!

Upvotes: 1

Views: 27

Answers (1)

Georges O.
Georges O.

Reputation: 992

You have several solutions.

1 - Call dynamically the variable

On a loop, I will create a variable with the name of the variable and call it dnamically by a double $$. I don't like this solution :)

<?php
$verbs_L1_occurr = ['a', 'b', 'c', 'a'];
$verbs_L2_occurr = ['a', 'b', 'c', 'b', 'b'];

for( $i = 1 ; $i < 2 ; $i++ ) { // iterate from 1 to 2
  $function = 'verbs_L' . $i . '_occcur';
  $$function = array_unique($$function);
}

2 - Use 3D arrays

(As said by Scott)

<?php // I use php 5.4
$verbs = [];
$verbs['L1'] = ['a', 'b', 'c', 'a'];
$verbs['L2'] = ['a', 'b', 'c', 'b', 'b'];

foreach( $verbs as $key => $values )
  $verbs[$key] = array_unique($values);

or just:

$verbs = array_map('array_unique', $verbs);

Upvotes: 1

Related Questions