I would use count() if they are the same, as in my experience it is more common, and therefore will cause less developers reading your code to say "sizeof(), what is that?" and having to consult the documentation.
I think it means sizeof() does not work like it does in C (calculating the size of a datatype). It probably made this mention explicitly because PHP is written in C, and provides a lot of identically named wrappers for C functions (strlen(), printf(), etc)
I would use count() if they are the same, as in my experience it is more common, and therefore will cause less developers reading your code to say "sizeof(), what is that?" and having to consult the documentation.
I think it means sizeof() does not work like it does in C (calculating the size of a datatype). It probably made this mention explicitly because PHP is written in C, and provides a lot of identically named wrappers for C functions (strlen(), printf(), etc)
According to phpbench:
Is it worth the effort to calculate the length of the loop in advance?
//pre-calculate the size of array
$size = count($x); //or $size = sizeOf($x);
for ($i=0; $i<$size; $i++) {
//...
}
//don't pre-calculate
for ($i=0; $i<count($x); $i++) { //or $i<sizeOf($x);
//...
}
A loop with 1000 keys with 1 byte values are given.
| count() | sizeof() | |
|---|---|---|
| With precalc | 152 | 212 |
| Without precalc | 70401 | 50644 |
(time in µs)
So I personally prefer to use count() instead of sizeof() with pre calc.
What is the primary function to get the PHP array length?
How do I properly use the PHP array length in a for loop?
";}
How does checking the PHP array length affect performance?
You can achieve this in this way as well.
<?php
$products = array('Volvo', 'BMW', 'Toyota', 'Kijang');
for(
i<count($products);$i++){
echo implode(", ",$products);
echo "<br>";
array_push($products, array_shift($products));
}
?>
This will give you the following result:
Volvo, BMW, Toyota, Kijang
BMW, Toyota, Kijang, Volvo
Toyota, Kijang, Volvo, BMW
Kijang, Volvo, BMW, Toyota
You can run the code in here.Hope this will help you.
You can achive it in this way
<?php
$products = array('Volvo', 'BMW', 'Toyota', 'Kijang');
foreach($products as $product){
echo "'".$product."', ";
foreach($products as $otherProduct){
if($otherProduct == $product){
// Skip the element
continue;
}
echo "'".$otherProduct."', ";
}
echo "<br>";
}
You need to loop twice to get the result.