Create Unique Array Based on Array Keys in File

Posted on 2011-04-24
Last Modified: 2012-05-11
I have data in a file that I use 'explode' get the keys/values.


I will need to loop through each line to get a unique list of the array keys.

how do I write the foreach rule in order to put the unique list of keys in one array?

thanks in advance.
Question by:deharvy
    LVL 39

    Expert Comment

    by:Pratima Pharande
    LVL 3

    Accepted Solution

    $file = fopen("keys.txt", "r") or exit("Unable to open file!");
    $keys = array();
          $line = fgets($file);
          $line = explode(",", $line);
          foreach ($line as $item)
                $item = explode("=", $item)
                $keys[$item[1]] = $item[0];            
    print_r($keys); //TESTING

    Author Closing Comment

    Thank you.
    LVL 107

    Expert Comment

    by:Ray Paseur
    Let's try to be clear on the terminology.  Are the numbers the "keys" here?  So that if you got unique keys you would have 1,2,3,4,5?  Would you care about apple vs orange (they both have the same key)?  Give us a little more to go on here, because the question looks very theoretical (even academic) and I have a feeling that there are practical matters that might influence the data structure.  What I am looking at here looks to me like it would be better suited to be XML, instead of a string of number=fruit pairs.

    Featured Post

    What Security Threats Are You Missing?

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Join & Write a Comment

    Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit ( and similar technologies have enjoyed wide adoption, making it possib…
    These days socially coordinated efforts have turned into a critical requirement for enterprises.
    The viewer will learn how to dynamically set the form action using jQuery.
    The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

    728 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now