0

I have a php script in the script I need to understand some code. Can you please guide me to understand the code: Here is the function from the PHP script:

function get_list_ip($ip_addr_cidr){
    $ip_arr = explode("/", $ip_addr_cidr);    
    $bin = "";

    for($i=1;$i<=32;$i++) {
        $bin .= $ip_arr[1] >= $i ? '1' : '0';   
    }

    $ip_arr[1] = bindec($bin);
    $ip = ip2long($ip_arr[0]);
    $nm = $ip_arr[1];
    $nw = ($ip & $nm);
    $bc = $nw | ~$nm;
    $bc_long = ip2long(long2ip($bc));

    for($zm=1;($nw + $zm)<=($bc_long - 1);$zm++)
    {
        $ret[]=long2ip($nw + $zm);
    }
    return $ret;
}

Here is the line I need to understand:

  1. $bin .= $ip_arr[1] >= $i ? '1' : '0'; what is mean by >=, ? and : here
  2. $nw = ($ip & $nm); what is & in variable
  3. $bc = $nw | ~$nm; what is | here
Sammitch
  • 30,782
  • 7
  • 50
  • 77

1 Answers1

1

Ternary operator

$bin .= $ip_arr[1] >= $i ? '1' : '0'

This shorthand comparisons is just another style of writing if conditions.

This is equivalent to:

if($ip_arr[1] >= $i){
   $bin .= '1';
} else {
    $bin .= '0';
}

Bitwise Operators

| is called OR

$a | $b: Bits that are set in either $a or $b are set.

& is called AND

$a & $b: Bits that are set in both $a and $b are set.

Reference

B001ᛦ
  • 2,036
  • 6
  • 23
  • 31