SitePoint Sponsor

User Tag List

Results 1 to 11 of 11
  1. #1
    SitePoint Member
    Join Date
    Apr 2009
    Posts
    13
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Help me, my first function

    Hi, everyone, I created my first function to judge whether an array is indexed, associative or mixed. Maybe there are some redundant contents or bugs in my code. Can you tell me how to trim it and how to write some appropriate comments. Any suggestion is welcome.

    PHP Code:
        function judge_array_index($array) {
            if(!
    is_array($array)):
                exit(
    'Your input is not an array.<br />');
            endif;
            
    $count_str 0
            
    $count_num 0
            
    reset($array);
            for(
    $i 0$i sizeof($array); $i++):
                if(
    is_string(key($array))):
                    
    $count_str++;
                elseif(
    is_integer(key($array))):
                    
    $count_num++;
                endif;
                
    next($array);
            endfor;
            
            if(
    $count_str == && $count_num == 0):
                echo 
    'The array is null.<br />';
            elseif(
    $count_str && $count_num == 0):
                echo 
    'The array is associative.<br />';        
            elseif(
    $count_str == && $count_num 0):
                echo 
    'The array is indexed.<br />';    
            elseif(
    $count_str && $count_num 0):
                echo 
    'The array is mixed.<br />';
            endif;
        } 

  2. #2
    SitePoint Member
    Join Date
    Oct 2008
    Posts
    18
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code looks clean and you don't really need to add comments as it is very straight forward.
    Free automatic directory submission
    Relieve stress and read more about stress relief.

  3. #3
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I would suggest to return the values instead of echoing the text inside the function itself something like following:
    PHP Code:
    function judge_array_index($array) {
        if(!
    is_array($array)):
            return 
    false;
        endif;
        
    $count_str 0
        
    $count_num 0
        
    reset($array);
        for(
    $i 0$i sizeof($array); $i++):
            if(
    is_string(key($array))):
                
    $count_str++;
            elseif(
    is_integer(key($array))):
                
    $count_num++;
            endif;
            
    next($array);
        endfor;
        
        if(
    $count_str == && $count_num == 0):
            return 
    'E'// E for empty array or something
        
    elseif($count_str && $count_num == 0):
            return 
    'A'// A for associative or something
        
    elseif($count_str == && $count_num 0):
            return 
    'I'// I for indexed array or something    
        
    elseif($count_str && $count_num 0):
            return 
    'M'// M for mixed array or something
        
    endif;

    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  4. #4
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    I would suggest something similar, though with constants. I would also recommend that you use the regular control structures instead of the alternative syntax.

    In fact, this is how I'd go around the same thing:
    PHP Code:
    <?php
    define
    ('JUDGE_ARRAY_ERROR'0);
    define('JUDGE_ARRAY_EMPTY'1);
    define('JUDGE_ARRAY_ASSOC'2);
    define('JUDGE_ARRAY_INDEX'3);
    define('JUDGE_ARRAY_MIXED'4);
    function 
    judge_array_index(array $array) {
        if(
    count($array) < 1) return JUDGE_ARRAY_EMPTY;
        
    $HasStringKey $HasNumericKey false;
        foreach(
    $array as $key => $value){
            if(
    $HasNumericKey && $HasStringKey){
                break;
            }else if(!
    $HasNumericKey && is_integer($key)){
                
    $HasNumericKey true;
            }else if(!
    $HasStringKey && is_string($key)){
                
    $HasStringKey true;
            }
        }
        switch(
    true){
            case 
    $HasNumericKey && $HasStringKey:
                return 
    JUDGE_ARRAY_MIXED;
            break;
            case 
    $HasNumericKey:
                return 
    JUDGE_ARRAY_INDEX;
            break;
            case 
    $HasStringKey:
                return 
    JUDGE_ARRAY_ASSOC;
            break;
            default:
                return 
    JUDGE_ARRAY_ERROR;
            break;
        }

    $array = array(=> 'something''one' => 'tree''two' => 'other');
    switch(
    Judge_Array_Index($array)){
        case 
    JUDGE_ARRAY_ASSOC:
            echo 
    'It\'s associative.';
        break;
        case 
    JUDGE_ARRAY_INDEX:
            echo 
    'It\'s indexed.';
        break;
        case 
    JUDGE_ARRAY_MIXED:
            echo 
    'It\'s both.';
        break;
        case 
    JUDGE_ARRAY_EMPTY:
            echo 
    'It\'s empty.';
        break;
        case 
    JUDGE_ARRAY_ERROR:
            echo 
    'There was an error :O.';
        break;
    }
    It can be laid out in a somewhat more concise fashion, but this is more learner-friendly.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  5. #5
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Just a quick thought to try and encapsulate those constants, what about an OO approach?

    I don't mean to take anything from the OP though, so apologies.

    PHP Code:
    <?php
    class JudgedArray extends ArrayObject
    {
        const 
    UNKWN 0;
        const 
    ASSOC 1;
        const 
    INDEX 2;
        const 
    MIXED 4;
        const 
    BLANK 8;
        
        protected 
    $iType;
        
        public function 
    __construct($aArray)
        {
            
    parent::__construct($aArray);
            
    /* Process and set iType */
        
    }
        
        public function 
    getType()
        {
            return 
    $this->iType;
        }
    }

    $oArray = new JudgedArray(range('a''z'));

    if(
    $oArray->getType() === JudgedArray::ASSOC)
    {
        echo 
    'it be an associative array';
    }
    ?>
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  6. #6
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    I can't see any benefit to an OOP approach though, in this situation. I suppose the encapsulation of the constants in the class/object.

    Generally I would use a bit-approach, i.e. 0,1,2,4,8,16,32 etc only when more than one can be satisfied, for example:
    PHP Code:
    define('EVEN'1);
    define('MORE_THAN_FIVE'2);
    define('DIVISIBLE_BY_TWENTY'4);
    define('LESS_THAN_ONE_HUNDRED'8);
    function 
    GetProperties($Number){
        
    $result 0;
        if(
    $Number &#37; 2 == 0){
            
    $result |= EVEN;
        }
        if(
    $Number 5){
            
    $result |= MORE_THAN_FIVE;
        }
        if(
    $Number 20 == 0){
            
    $result |= DIVISIBLE_BY_TWENTY
        
    }
        if(
    $Number 100){
            
    $result |= LESS_THAN_ONE_HUNDRED;
        }
        return 
    $result;

    You would then use bitwise operators to see if certain conditions are satisfied - which would be a more efficient approach than the one I posted above.

    The question is, though, why use the bit pattern when no bitwise methodology is involved?
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  7. #7
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    It was merely a poor choice of constant values.

    I just typed them without thinking, my intention wasn't to hint at bitwise computations.

    As stated in my post, I thought using an object would be a good way to isolate the constants.

    Ho hum.
    Last edited by AnthonySterling; Apr 17, 2009 at 09:10.
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  8. #8
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Decide what you want to happen if it gets called without a value.
    PHP Code:
    ..doing things ..

    // oops, someone just twittered ...
    judge_array_index();

    ... 
    carried on doing things ... as you do 

  9. #9
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Ok, this is an improvement on my existing code above, using an object instead and using Bitwise methods:
    PHP Code:
    <?php
    Class ArrayJudger{
        Const 
    ASSOC 1;
        Const 
    INDEX 2;
        Protected 
    $Judgement;
        Protected 
    $Array;
        Public Function 
    __Construct(Array $Array = array()) {
            
    $this->SetArray($Array);
        }
        Public Function 
    SetArray(Array $Array){
            
    $this->Array $Array;
            
    $Judgement =& $this->Judgement;
            
    $Judgement 0;
            foreach(
    Array_Keys($Array) as $Key){
                
    $Index self::INDEX $Judgement;
                
    $Assoc self::ASSOC $Judgement;
                if(
    $Index && $Assoc){
                    break;
                }else if(!
    $Index && Is_Integer($Key)){
                    
    $Judgement |= self::INDEX;
                }else if(!
    $Assoc && Is_String($Key)){
                    
    $Judgement |= self::ASSOC;
                }
            }
        }
        Public Function 
    GetArray(){
            return 
    $this->Array;
        }
        Public Function 
    GetJudgement(){
            return 
    $this->Judgement;
        }
        Public Function 
    GetMessage(){
            
    $Judgement $this->GetJudgement();
            
    $Assoc $Judgement self::ASSOC;
            
    $Index $Judgement self::INDEX;
            if(
    $Assoc && $Index){
                return 
    'Mixed Array';
            }else if(
    $Assoc){
                return 
    'Associative Array';
            }else if(
    $Index){
                return 
    'Indexed Array';
            }else{
                return 
    'Empty Array';
            }
        }

    $Array = Array('hello''a' => 'world');
    $ArrayJudger = new ArrayJudger($Array);
    echo 
    $ArrayJudger->GetMessage();
    Of course, OP, this isn't the typical solution - I think it's more of a proof-of-concept post more than anything. Your function works fine as it is

    I have a feeling this is going to turn into one of those 'find how many ways to accomplish...' threads :P
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  10. #10
    SitePoint Addict
    Join Date
    Jul 2008
    Posts
    213
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    For someone who has wanted to learn OO, it is nice to see how some procedural code can be "converted" to OO code, and in different styles too.

  11. #11
    SitePoint Wizard REMIYA's Avatar
    Join Date
    May 2005
    Posts
    1,351
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I like SilverBulletUK approach. Just a bit more cleaner solution using a static function, instead of constructor:

    Code PHP:
    [COLOR=Black]<?php
    class JudgedArray extends ArrayObject{
        const UNKWN = 0;
            const ASSOC = 1;
            const INDEX = 2;
        const MIXED = 4;
        const BLANK = 8;
        public static function type($aArray){
            /* Process and return type */
        }
    }
    [/COLOR][COLOR=Black]
    if([/COLOR][COLOR=Black]JudgedArray::type[/COLOR][COLOR=Black]([/COLOR][COLOR=Black]range('a', 'z')[/COLOR][COLOR=Black]) === JudgedArray::ASSOC){
        echo 'it be an associative array';
    }
    ?>[/COLOR]


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •