3

I have an array that looks like this:

$array = array(
   array('name' => 'number1', 'number' => '0612345675'),
   array('name' => 'number2', 'number' => '0634345675'),
   array('name' => 'number3', 'number' => '0634378675')
);

Now I have this number: 0634345675.
How can I check If this number exists in the array $array?

I tried to do this:

if(!in_array('0634345675', $array)){
   // insert into DB
}

But this keeps adding multiple of the same rows.
Does anyone knows how to check if this number exists in $array?

Full code:

foreach($DN as $number){ // $DN got ['0634345675', '0632545675', '0614342375']
    if(!in_array($number, $array)){
       // insert into DB
    }
}
Webdeveloper_Jelle
  • 2,868
  • 4
  • 29
  • 55
  • [This answer](https://stackoverflow.com/a/29233744/5209435) looks like what you want, or at least can be adapted very easily. – Matt Stannett May 31 '19 at 07:58

1 Answers1

8

You have to use in_array() along with array_column()

<?php

$array = array(
   array('name' => 'number1', 'number' => '0612345675'),
   array('name' => 'number2', 'number' => '0634345675'),
   array('name' => 'number3', 'number' => '0634378675')
);

$valueToFind = '0634345675';

if (in_array($valueToFind, array_column($array, 'number'))){
    echo 'found';
}else{
    echo 'not found';
}

Output:- https://3v4l.org/TUtSL

If you want to show that array too, then use array_search()

$key = array_search($valueToFind, array_column($array, 'number'));
if($key){
    echo 'value found';
    echo PHP_EOL;
    echo "matched array is";
    echo PHP_EOL;
    print_r($array[$key]);
}

Output:-https://3v4l.org/Mc2cC

In case multiple match found:

$valueToFind = '0634378675';

$matchedArray = array();
foreach($array as $arr){
    if($valueToFind == $arr['number']){
        $matchedArray[] = $arr;
    }
}

if( count($matchedArray) > 0){
    echo "match found";
    echo PHP_EOL;
    print_r($matchedArray);
}

Output:- https://3v4l.org/p439T

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98