lustfulglances lustfulglances - 7 months ago 9
PHP Question

How do I get the value of the 3rd element of this array in php?

I'm getting a bit confused here. I'm able to get all the array values, or just one by specifying the number, but I cant figure out how to get the value of the element called "flag" in the array. I'm new to arrays in general and trying to learn all the terminology, but I cant seem to accomplish what I need. Here is the array:

Array
(
[0] ( Array
(
[id] => 1
[name] => Bag
[flag] => 0
)

[1] => Array
(
[id] => 2
[name] => Screen
[flag] => 0
)

[2] => Array
(
[id] => 3
[name] => HD
[flag] => 0
)

)


To get that output, I typed:

print_r(array_values($items));


If I type (which I understand where this is pulling from):

print_r(array_values($items[1]));


Then I get:

Array
(
[0] => 2
[1] => Screen
[2] => 1
)


What I need to get is the value of the "flag" (3rd) column in this array. I'm just not sure how to get that value. The array will always be pulling in this order from the mysql database. I basically am trying to do something like this:

if ($array[1].[flag]==1){
echo "Flag is true";
}else{
echo "Flag is false";
}


I'm just not sure how to specify that 3rd element.

Thanks

Answer

If you mean the third element in the Array of sub-arrays then you do it like this:

$thirdItem = $items[2]

if from third element you mean the subarray with id = 3 then

function getItemByID( $items, $id ) {
   for( $i = 0; $i < count( $items ); $i ++ ) {
      if( $items[$i]['id'] == $id ) return $items[$i];
   }
}

$item = getItemByID( $items, 3 );

if from 3rd element you mean value of flag in subarray 3

$value = $items[2]['flag'];

or

$value = $thirdItem['flag']

I hope that helps!