Blogger Information
Blog 5
fans 0
comment 0
visits 2469
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP第一课
FILE2021
Original
574 people have browsed it

JS中的for,foreach和PHP中的foreach

JS中的for

  1. <script>
  2. let arr = ['huawei','apple','xiaomi'];
  3. console.log(arr);
  4. for(let i = 0; i<arr.length;i++){
  5. // alert(arr[i]);
  6. console.log(arr[i]);
  7. }
  8. for (let index=0;index<arr.length;index++){
  9. console.log(arr[index]);
  10. }

</script>


JS中的foreach

  1. <script>
  2. let arr = [1,2,3,4,5,6,7];
  3. arr.forEach((item, index) => (console.log(arr[index])));

</script>


PHP中的foreach

  1. <?php
  2. $arr = ['xiaomi','huawei','apple'];
  3. for($i = 0; $i<count($arr);$i++){
  4. echo $arr[$i].'<br />';
  5. };
  6. echo '<hr />';
  7. $arr2 = [];
  8. foreach($arr as $k=>$v){
  9. echo $k.'=>'.$v.'<br />';
  10. array_push($arr2,$v); ///往数组中添加元素
  11. };
  12. print_r($arr2);
  13. ?>
Correcting teacher:灭绝师太灭绝师太

Correction status:qualified

Teacher's comments:对比php 中 for foreach遍历数组的速度发现, 在实际项目中尽量使用foreach去遍历php数组, 因为产生的是临时变量, 遍历结束后会被释放, 相比于for遍历数组来说速度更快~
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post