Output of two programs: Applying intval on arrays

Hi,
I found following programs from internet, the first program is:

<?php 
$d = array(); 
echo intval($d) . "<br>"; 
$e = array("red", "green", "blue"); 
echo intval($e) . "<br>"; 
?>

Its giving me the output:

0
1

I can’tunderstand the correct reason. I am just guessing that in the first case the array is empty so I got 0 but in the second case, array has elements so its printing ‘1’.

The second program is:

<?php 
function min_values_not_zero(Array $values)  {   return min(array_diff(array_map('intval', $values), array(0)));
 } 
print_r(min_values_not_zero(array(-1,0,1,12,-100,1))."\n"); 
?>

I have two questions:

  1. What is the logic of using ‘intval’ in the 2nd program because all the array values are already integer values.
    2)what array_diff is doing? My answer is that it is substracting each value of $values array with ‘0’. But I am not sure.

Somebody please guide me.

Zulfi.

The free online PHP manual has a detailed explanation and also numerous examples which may be helpful:

https://www.php.net/manual/en/function.intval.php

1 Like

Was this here?

Further down the page it says:
" The integer value of the variable on success, 0 on failure. An empty array will return 0, and a non-empty array will return 1"

1 Like

It is producing an array that is the difference between (array_map('intval", $values) and an array that simply contains a zero. In other words, it is remving the zero from the array.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.