Using PHP Array in Foreach -
i have 2 arrays: $users[] , $types[]
with return result this:
users = array ( [0] => 1 [1] => 1 [2] => 1 ) types = array ( [0] => 0 [1] => 1 [2] => 0 )
how can call them $user['0] , $types['0] in foreach ? want return them this:
1,0
1,1
1,0
foreach ($users $index => $code) { // return users first number echo $code; // want here return type first number of array aswell? }
thanks,
it's easy:
foreach ($users $index => $code) { echo $users[$index].', '.$types[$index]; }
if it's possible, each array contains different number of elements (or better don't know, how many items each array contains), should check, if particular element exists in second array:
foreach ($users $index => $code) { echo $users[$index].', '.(isset($types[$index]) ? $types[$index] : 'doesn\'t exist'); }
you can use example for
loop:
// array indexes start 0, if they're not set explicitly else ($index = 0; $index < count($users); $index++) { echo $users[$index].', '.(isset($types[$index]) ? $types[$index] : 'doesn\'t exist'); }
if wouldn't check, if particular element exists in second array, php produce error of type notice, tells you're accessing undefine offset:
php notice: undefined offset: x in script.php on line y
where x index (key), exists in first array, doesn't exists in second array.
note: should develop enabled displaying of all types of errors, notices, , always check if particular index exists in array, if you're not sure (e.g. array comes user input, database etc.).
Comments
Post a Comment