0

I have two arrays: $users[] and $types[]

With return result like this:

Users = Array ( [0] => 1 [1] => 1 [2] => 1 )
Types = Array ( [0] => 0 [1] => 1 [2] => 0 )

How i can call them like $user['0] and $types['0] in foreach ? I want to return them like this:

1,0
1,1
1,0

foreach ($users as $index => $code) {
  // this return users first number
  echo $code;

 // i want here to return type first number of array aswell?
}

Thanks,

1
  • If any of answers helped you to solve your problem, please mark it as an answer. It'll help others to easily find information they need. You can read how to do it on link RiggsFolly sent you in the comment to my answer. Commented Aug 31, 2015 at 13:50

2 Answers 2

2

It's easy:

foreach ($users as $index => $code)
{
    echo $users[$index].', '.$types[$index];
}

If it's possible, that each array contains different number of elements (or better you just simply don't know, how many items each array contains), you should also check, if particular element exists in second array:

foreach ($users as $index => $code)
{
    echo $users[$index].', '.(isset($types[$index]) ? $types[$index] : 'doesn\'t exist');
}

You can also use for example for loop:

// array indexes start from 0, if it they're not set explicitly to something else
for ($index = 0; $index < count($users); $index++)
{
    echo $users[$index].', '.(isset($types[$index]) ? $types[$index] : 'doesn\'t exist');
}

If you wouldn't check, if particular element exists in second array, PHP would produce an error of type notice, which tells you that you're accessing undefine offset:

PHP Notice: Undefined offset: X in script.php on line Y

Where X is an index (key), which exists in first array, but doesn't exists in second array.

Note: you should always develop with enabled displaying of all types of errors, even notices, and always check if particular index exists in an array, if you're not sure (e.g. array comes from user input, database etc.).

Sign up to request clarification or add additional context in comments.

1 Comment

@Seik Thanks for the upvote, but read that link RiggsFolly posted, please. Upvote is nice, but the punchline is in marking it as an answer.
0

I think I get what you are asking. You could try this

foreach ($users as $i => $element){
    echo $users[$i].', '.$types[$i];
}

That will give you what you are looking for.

1 Comment

Thanks Guys, this method is working great ! It was easy solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.