Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How can i print values of array in this program? it is printing the key?

    • 0
    • 0
    • 0
    • 2
    • 0
    • 0
    • 0
    • 402
    Answer it

     In program below, I  want to print values of array but it is printing the key, can someone help.

    <?php
    
    $CHAMP = array("ESP"=>"BARCELONA", "GER"=>"BAYERN", "POR"=>"BENFICA","ENG"=>"CHELSIA");
    $TEAM = array("ESP"=>"ATLETICO", "GER"=>"LEVERKUSEN", "POR"=>"PORTO","ENG"=>"ARSENAL","ESP"=>"REAL MADRID");
    $A=array_keys($CHAMP);
    $B=array_keys($TEAM);
    
    for ($i = 0; $i <count($CHAMP); $i++)
            {
        
                for($j=0;$j<=count($TEAM);++$j)
                {
                    if($A[0] == $B[$j])
                    {
                    shuffle($B);
                    }
                    else
                    {
                        shuffle($A);
    
                        print_r($B[$j]);
                        break;
                }
                }
            }
            
            ?>

     

 2 Answer(s)

  • No matter which loop you use, you just need proper format to get key/value
    <?php
    $CHAMP = array("ESP"=>"BARCELONA", "GER"=>"BAYERN", "POR"=>"BENFICA","ENG"=>"CHELSIA");
    $TEAM = array("ESP"=>"ATLETICO", "GER"=>"LEVERKUSEN", "POR"=>"PORTO","ENG"=>"ARSENAL","ESP"=>"REAL MADRID");
    $keys = array_keys($TEAM);
    $TEST = array("ESP"=>"BARCELONA", "GER"=>"BAYERN","ENG"=>"ARSENAL","ESP"=>"REAL MADRID");
    
    while (list($key, $val) = each($CHAMP)) {
    	print "While loop: $key is $val\n";
    }
    for ($i = 0; $i < count($TEAM); ++$i) {
    	print "For loop: ".$keys[$i]." is ".$TEAM[$keys[$i]]."\n";
    }
    foreach($TEST as $key => $val) {
    	print "Foreach loop: $key is $val\n";
    }
    
    ?>
    
  • Hello Basant,

    I just go through your code and i found that you are retrieving keys using array_key function and using for loop then. you need to use the foreach loop to retrieve the both keys as well as values. Kindly check the code below.

    <?php
    $arr = array('name'=>'Deepak','designation'=>'Software Engineer');
    foreach($arr as $key=>$val){
    echo $key. "\t" . $val;
    }
    ?>
    

    Thank You

    Deepak Verma

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: