php - Better way to print out data from only the first index in an array full of objects? -


option 1:

$foo = array($obj1, $obj2, $obj3); ($i = 0; $i < 1; $i++) {     echo $foo[$i]->attribute;     echo $foo[$i]->attribute2; } //shows obj1's attribute , attribute2 

option 2:

$foo = array($obj1, $obj2, $obj3); $first_foo = array_shift($foo); /* have first index in new array */ foreach ($first_foo $object) {     echo $object->attribute;     echo $object->attribute2; } //shows obj1's attribute , attribute2 

option 3:

$foo = array($obj1, $obj2, $obj3); $first_foo = $foo[0] /* have object, obj1 */ echo $first_foo->attribute; echo $first_foo->attribute2; //shows obj1's attribute , attribute2 

i used option 3, of these feel kinda lacking... how this? loop in options 1 , 2 worth if feel pulling first 2 instead of 1 later on? i.e. pulling latest news article vs. pulling latest 2 etc.

why complicated?

loops, array_shift(), ... it's not neccessary.

you gave solution yourself:

$foo[0]->attribute 

another 1 be

reset($foo)->attribute 

on edit:

if want write code flexible later, do

$need = 1; // variable number of elements need for($i = 0; $i < $need; $i++)     echo $foo[$i]->attribute; 

Comments

Popular posts from this blog

c# - Operator '==' incompatible with operand types 'Guid' and 'Guid' using DynamicExpression.ParseLambda<T, bool> -