1

Alright, so I'm querying the DB and generating an array from a list of IP addresses:

$q = 'SELECT ip FROM proxy'; $r = mysqli_fetch_all($con->query($q), MYSQLI_ASSOC); 

Array returned looks like this:

Array ( [0] => Array ( [ip] => 1.202.244.222 ) [1] => Array ( [ip] => 1.226.238.136 ) [2] => Array ( [ip] => 1.228.231.247 ) [3] => Array ( [ip] => 1.238.106.137 ) [4] => Array ( [ip] => 1.238.155.191 ) 

But if I want to find say the first or any IP in the above list, for some reason it doesn't find anything:

$ip = "1.202.244.222"; if(in_array($ip,$r)) { echo "gotcha"; } 

What am I doing wrong here?

1
  • It's an array of an array... Collapse the thing, and then it'll work. There are a couple of options here: stackoverflow.com/questions/526556/… Commented Aug 13, 2017 at 8:31

5 Answers 5

2

Got confused by the array within array stuff which I didn't notice at first. Thanks to Zeth's pointers, I got it to work by collapsing the arrays into one by adding:

$r0 = array_column($r, 'ip'); 

And then:

if(in_array($ip,$r0)) { echo "gotcha"; } 
Sign up to request clarification or add additional context in comments.

Comments

1

It's an array of arrays... Collapse the thing, and then it'll work. There are a couple of options here: How to "flatten" a multi-dimensional array to simple one in PHP?

Comments

1

The most flexible approach for such situations is to use a user defined comparison function:

<?php $needle = '1.202.244.222'; $haystack = [ [ 'ip' => '1.202.244.222' ], [ 'ip' => '1.226.238.136' ], [ 'ip' => '1.228.231.247' ], [ 'ip' => '1.238.106.137' ], [ 'ip' => '1.238.155.191' ] ]; $result = array_filter($haystack, function($entry) use ($needle) { return isset($entry['ip']) && $needle === $entry['ip']; }); print_r($result); 

The output of above code obviously is:

Array ( [0] => Array ( [ip] => 1.202.244.222 ) ) 

Comments

0

Your Array condition was wrong.

 $ip_find = '1.202.244.222'; $ip_values = [ [ 'ip' => '1.202.244.222' ], [ 'ip' => '1.226.238.136' ], [ 'ip' => '1.228.231.247' ], [ 'ip' => '1.238.106.137' ], [ 'ip' => '1.238.155.191' ] ]; foreach ($ip_values as $key => $value) { foreach ($value as $key => $ip) { if ($ip==$ip_find) { echo $ip." Gocha"; break; } } } 

Comments

0

You can do it using foreach:

$r = [ [ 'ip' => '1.202.244.222' ], [ 'ip' => '1.226.238.136' ], [ 'ip' => '1.228.231.247' ], [ 'ip' => '1.238.106.137' ], [ 'ip' => '1.238.155.191' ] ]; $ip = "1.202.244.222"; foreach($r as $elem) { if($elem['ip'] == $ip) { echo "gotcha"; break; } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.