PHP Array - Print Specific Data

Associate
Joined
27 Jun 2008
Posts
1,538
I have data taken from a database which is then pushed into an array called $lr using array_push() in a while loop. Instead of just printing all the data in the array I only wanted it to print the data of $lr[0][1] where the element $lr[0][0] = 1.

PHP:
Array
(

    [0] => Array
        (
            [0] => 1
            [1] => Something1
        )

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

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

)

So based on the above example I only want it to output:

Something1
Something3

I'm not sure how to go about doing this. I thought it might need to be placed into a for or while loop until it reached the end of the array. I know I could just do this with multiple SQL calls but thought it'd be better to simple sort the array in some way.
 
PHP:
foreach($array as $node) {
	if ($node[0] == 1) {
		echo $node[1];
	}
}

alternatively, you can define a lambda function to be applied to each element.
 
If you have lots of array items you could save yourself some CPU time with:

PHP:
foreach($array as $node) {
    if ($node[0] == 1) {
        echo $node[1];
        break;
    }
}
 
Back
Top Bottom