The sizeof function in php is an alias of count (), like count (), it receives the number of key-value arrays or objects. The required parameter is an array or an object; optional, the second value is COUNT_RECURSIVE, or 1 (by default, 0); if set, it is considered recursively.
PHP: how to reduce the number of iterations in a loop and reduce script execution time?
Since count () and sizeof php are used very often in loops, you should study them thoroughly.
$array = array( "fruit" =>array( "apple", "bananas", "orange", ), "vegetables" =>array( "potatoes", "tomatoes", ), ); echo " = ".sizeof($array);
Testing large arrays in a loop (more than 65,000 elements) showed that sizeof () is faster than count (), so it makes sense to put it into practice.
In loops, it is always better to replace sizeof php with a variable, because otherwise the size of the array will be determined in each iteration, which slows down the process.
$test = array( 1, 2, 3, 4 ); $sizeof_test = sizeof( $test ); for ( $it=0; $it < $sizeof_test; $it++ ) { echo $test[$it]; }
If you test a cycle at 1000 single-byte values, then its transit time with a predefined variable is less than 250 times.
Consider an array with zero values:
$test2 = array( '', null, false, 0 ); var_dump( sizeof( $test2 ) );
As you can see from the example, sizeof php (and count too) consider the number of elements, including zero, so you need to take this into account and (if necessary) delete empty values โโusing array_filter or another user-defined function.
Add an array to $ test2:
$test2 = array( '',null,false,0, array() );
In this example, array_filter deleted all the empty values โโof the one-dimensional array, but this function has no recursive action, so the "null" value of the "internal" array remains, which means sizeof php takes it into account.
Let's see what happens if you remove array_filter?
$test2 = array('', null, false, 0, array() );
If empty values โโwere not intentionally entered into the code, then it is better to get rid of them with the help of filter functions before starting the cycle. This will remove unnecessary iterations of the loop and reduce the time it takes to complete the process.
How to count StdClass object created from json_decode using sizeof php?
$json = '{ "foo": "bar", "number": 10 , "car": "BMW" }'; $stdInstance = json_decode( $json ); var_dump( sizeof( ( array )$stdInstance ) );
Sizeof () determines the number of elements in an array or Countable. StdClass is neither one nor the other. To get an object as an array, use the get_object_vars function. The first option with (array) also works, but still the second option seems more reliable.
Get_object_vars is used to obtain non-static properties of the object, which is quite suitable for our example.