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?
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.
We can get the array index by using the array_search() function. This function is used to search for the given element.
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.
array_keys() will print indexes in array.
print_r(array_keys($arr));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With