Reputation: 3783
I struggle to access specific item within my PHP array, which is created like this array('expected' => array('form', 'title'))
.Array
(
[expected] => Array
(
[0] => form
[1] => title
)
)
I would like to access the title of the first array (expected) as well as the value of the element within this array (form and title)
I tried methods such as array_values()
or key
but I never get the right results.
EDIT Thanks to Aamir, this problem is solved. In fact, it was because I pass the array as a parameter into a method and I set it to null by default. Yes I know, dumb stuff.
Upvotes: 0
Views: 112
Reputation: 6539
Use below code:-
$my_array = Array
(
'expected' => Array
(
'0' => 'form',
'1' => 'title'
)
);
echo $form = $my_array[key($my_array)][0]; // print form
echo $title = $my_array[key($my_array)][1]; //print title
Hope it will help you :)
Upvotes: 0
Reputation: 1217
try this:
<?php
$array = array('expected' => array('form', 'title'));
function testFunc($array)
{
foreach ($array as $key=>$value) {
if(is_string($key))
{
echo $key."<br>";
}
if(is_string($value))
{
echo $value."<br>";
}
if(is_array($value))
{
testFunc($value);
}
}
}
testFunc($array);
?>
output:
expected
form
title
Upvotes: 0
Reputation: 96159
The question is vague enough to be answered by: Use a RecursiveTreeIterator
<?php
$x = array(
'level1' => array(
'item1.1',
'level2'=>array(
'item2.1',
'item2.2',
'level3'=>array(
'item3.1'
)
),
'item1.2'
)
);
$it = new RecursiveTreeIterator( new RecursiveArrayIterator($x), RecursiveIteratorIterator::SELF_FIRST );
foreach($it as $line) {
echo $line, PHP_EOL;
}
prints
\-Array
|-item1.1
|-Array
| |-item2.1
| |-item2.2
| \-Array
| \-item3.1
\-item1.2
You might want to refine your question....
Upvotes: 2
Reputation: 4564
Try this :
$array = array('expected' => array
(
0 => 'form',
1 => 'title',
)
);
$expected= $array['expected'];
$form = $expected[0];
$title = $expected[1];
Upvotes: 0
Reputation: 326
foreach($array as $key => $value){
echo $key; //expected
echo $value[0]; //form
echo $value[1]; //title
//OR if you have more values then
foreach ($value as $key1 => value1){
echo $value1; //form in 1st iteration and title in 2nd iteration
}}
Upvotes: 1