Search code examples
phpini

how to use php with ini files


My php Code here

 <?php
    function String($word){


            $lang = parse_ini_file("../pard_language/en/language.ini");

        $key = array_search($word, $lang); 
        if(isset($key)){
        echo $key;

        }
        }


     echo String("PARD_INSTALL");
    ?>

my language.ini file is this

PARD_INSTALL = Install
PARD_USER_AGGREMENT = User Aggrement
PARD_AGREE = Agree
PARD_HOST_NAME = Host Name
PARD_DATA_BASE = Data Base
PARD_DATA_BASE_USER =  Data Base User
PARD_DATA_BASE_USER_PASS_WORD =  Data Base User Password
PARD_CONNECT = Connect
PARD_RESET = Reset
PARD_ADMIN_USER_NAME =  Admin User Name
PARD_ADMIN_USER_PASS_WORD =  Admin User Password
PARD_LOGIN = Login

This my above code is not working.I want to keep a ini file which contain language contain and need to get the word value using above php function.This codes not give any output.please help me to solve this ?


Solution

  • You are searching for values not getting the key, parse_ini_file would return an array of all elements so with $lang[$word] you should get the values you want ...

    function String($word) {
        $lang = parse_ini_file("../pard_language/en/language.ini");
        return isset($lang[$word]) ? $lang[$word] : null ;
    }
    

    Now that is still a BAD Approach why ?

    • You have to call parse_ini_file every time you want a which loads the files every time
    • String is a bad name for a function
    • echo was called twice .. 1. In the function and outside the function insted of using return

    Here is what i would use :

    $ini = new ArrayINI("../pard_language/en/language.ini");
    echo $ini("PARD_INSTALL");
    // or
    echo $ini['PARD_INSTALL'];
    

    Because i also extended IteratorAggregate i can loop all the values

    foreach ( $ini as $k => $value ) {
        var_dump($k . " = " . $value);
    }
    

    Class Used

    class ArrayINI implements ArrayAccess, IteratorAggregate {
        private $lang;
    
        public function __construct($ini) {
            $this->lang = parse_ini_file($ini);
        }
    
        function __invoke($offset) {
            return $this->offsetGet($offset);
        }
    
        public function getIterator() {
            return new ArrayIterator($this->lang);
        }
    
        public function offsetSet($offset, $value) {
            if (is_null($offset)) {
                $this->lang[] = $value;
            } else {
                $this->lang[$offset] = $value;
            }
        }
    
        public function offsetExists($offset) {
            return isset($this->lang[$offset]);
        }
    
        public function offsetUnset($offset) {
            unset($this->lang[$offset]);
        }
    
        public function offsetGet($offset) {
            return isset($this->lang[$offset]) ? $this->lang[$offset] : null;
        }
    }