Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print or echo the array index of in PHP

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?

like image 966
Ali Avatar asked Jun 20 '12 18:06

Ali


People also ask

How do I print an array by index value?

You can access an array element using an expression which contains the name of the array followed by the index of the required element in square brackets. To print it simply pass this method to the println() method.

How do you get the index of an element in an array in PHP?

We can get the array index by using the array_search() function. This function is used to search for the given element.

How do you echo an array value?

To echo an array, use the format echo ${Array[0]}. Array is your array name, and 0 is the index or the key if you are echoing an associative array.


2 Answers

array_keys() will print indexes in array.

print_r(array_keys($arr));
like image 191
Somnath Muluk Avatar answered Oct 05 '22 05:10

Somnath Muluk


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
like image 27
Damien Pirsy Avatar answered Oct 05 '22 03:10

Damien Pirsy