0

I'm passing data from my controller to view, I have code in my view

foreach ($mapData as $map)
{
 echo $map['x'].';'.$map['y'].'<br/>';
}

And it prints me something like

5;5
6;6
7;7

Now, I am passing another data from my database as a two-dimensional array which looks like something like this

Array
(
[0] => Array
    (
        [x] => 5
        [y] => 4
    )

[1] => Array
    (
        [x] => 5
        [y] => 5
    )

)

I want to check if any of $map['x'] and $map['y'] exists in that array so I am doing (Don't know any other way because I need to check this in foreach loop)

if (in_array(array($map['x'], $map['y']), $array)) {
echo 1;
}

But it doesn't work and according to http://php.net/manual/en/function.in-array.php it should work? What am I doing wrong?

2
  • Shouldn't it be $mapData instead of $array? (perhaps you just used it as an example) Commented Aug 4, 2013 at 21:49
  • No, $array is different array than $mapData.. I already have an answer, thanks anyway. Commented Aug 4, 2013 at 22:00

2 Answers 2

1
Array
(
[0] => Array
    (
        [x] => 5
        [y] => 4
    )

[1] => Array
    (
        [x] => 5
        [y] => 5
    )

)

should look like

Array
(
[0] => Array
    (
        [0] => 5
        [1] => 4
    )

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

)

That means, $array (i.e. haystack) should not be an array with different indexing than neddle.

You are passing index x and y as haystack. But in needle you are just passing like array(5,5) or array(6,6) and so on.

According to doc, in_array() can compare

in_array( array(5,5), array( array(5,5), array(6,6) ) )

but not

in_array( array(5,5), array( array('x' =>5, 'y' => 5), array('x' => 6, 'y' => 6) ) )
Sign up to request clarification or add additional context in comments.

Comments

0

in_array is working properly, it's just that you're comparing an array without keys to an array that has an x and y as keys for their values. Try giving our new array the corresponding keys and then comparing:

if (in_array(array('x' => $map['x'], 'y' => $map['y']), $array)) {
    echo '1';
}

Comments

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.