Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Be sure to have unique array entry

I have a file which contains something like :

toto;145
titi;7
tata;28

I explode this file to have an array. I am able to display the data with that code :

foreach ($lines as $line_num => $line) {
    $tab = explode(";",$line);
    //erase return line
    $tab[1]=preg_replace('/[\r\n]+/', "", $tab[1]);
    echo $tab[0]; //toto //titi //tata
    echo $tab[1]; //145 //7 //28
}

I want to be sure that data contained in each $tab[0] and $tab[1] is unique.

For example, I want a "throw new Exception" if file is like :

toto;145
titi;7
tutu;7
tata;28

or like :

toto;145
tata;7
tata;28

How can I do that ?

like image 719
Bellami Avatar asked Jan 24 '26 11:01

Bellami


1 Answers

Convert your file to array with file(), and convert to associative array with additional duplication checking.

$lines = file('file.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$tab = array();
foreach ($lines as $line) {
    list($key, $val) = explode(';', $line);
    if (array_key_exists($key, $tab) || in_array($val, $tab)) {
        // throw exception
    } else {
        $tab[$key] = $val;
    }
}
like image 129
flowfree Avatar answered Jan 26 '26 00:01

flowfree