How to print or echo the array index of in PHP

2020-07-11 10:12发布

问题:

I'm trying to complete my assignment and this is the last thing to do now.

I know if I want to print the whole array I can just use foreach and many different method to print the entire array

foreach($v as $k=>$variable_name) { echo "<p> This is index of $k. value is $variable_name <br/></p>";}

But what if I want to only print each index separately?

I want to do the error message under each form so that is why I want each of them separate.

I tried with $v[0] and nothing appear.

is there a trick or something am I missing?

回答1:

If you're talking about an associative array, you need to fetch the index directly:

Example:

$array = array ('test' => 'value1', 'test2' => 'value2');   
echo $array['test']; // value1

You can do a print_r($array) to see the array structure nicely formatted:

<pre>
<?php print_r($array);?>
</pre>

What you're doing instead is fetch a value by its numerical index, like in

$array = array('test','test2','test3');
echo $array[0];  // test

On a further note, you can check beforehand if a key exists using array_key_exists():

var_dump(array_key_exists('test2',$array));  // (bool) TRUE


回答2:

array_keys() will print indexes in array.

print_r(array_keys($arr));


回答3:

I believe you're looking for this: http://php.net/manual/en/function.array-keys.php

Try (from the above page):

<?php
  $array = array(0 => 100, "color" => "red");
  print_r(array_keys($array));

  $array = array("blue", "red", "green", "blue", "blue");
  print_r(array_keys($array, "blue"));

  $array = array("color" => array("blue", "red", "green"),
               "size"  => array("small", "medium", "large"));
  print_r(array_keys($array));
?>


回答4:

You can use php array_keys function to get all keys. If Its Associative Array,

$array = array("color" => array("blue", "red", "green"),
               "size"  => array("small", "medium", "large"));
print_r(array_keys($array));

output will be :

Array
(
    [0] => color
    [1] => size
)

Other way is :

if(is_array($v){
    foreach($v as $k=>$value) { 
         echo "<br/>". $k ;  // $k is the key 
    }
}


回答5:

If you're using the foreach loop then you're probably using an associative array (i.e. $v['inputName']) So, using $v[0] wouldn't work because the indexes aren't defined by numbers - they are defined by lettering. You could use a foreach loop to then associate all the values to the numbered indexes and then us it like that.

$x = array();
foreach($v as $key=>$value) {

   $x[count($x)] = $key;

}

echo $x[0];

In that case $x[0] would work



回答6:

use print_r function to print the array :

print_r($array)