Home > other >  PHP add array value after echoed
PHP add array value after echoed

Time:09-28

I'm creating a web app where i want to include JavaScript files with all file sources in array, but I can't do that, Please Help

My Code

Header.php

<head>
<?php
  $import_scripts = array(
    'file01.js',
    'file02.js'
  );

  foreach ($import_scripts as $script) {
    echo '<script src="' . $script . '"></script>';
  }
?>
</head>
<body>

Index.php

<?php
  include('header.php');
  array_push($import_scripts,'file03.js')
?>

But this only including file01.js and file02.js, JavaScript files.

Sorry if you are having trouble understanding this

CodePudding user response:

Your issue is that you've already echo'ed the scripts in headers.php by the time you push the new value into the array in index.php. So you need to add to extra scripts before you include headers.php. Here's one way to do it (using the null coalescing operator to prevent errors when $extra_scripts is not set):

header.php

<?php
  $import_scripts = array_merge(array(
    'file01.js',
    'file02.js'
  ), $extra_scripts ?? []);

?>
<!DOCTYPE html>
  <html>
    <head>
      <!-- Scripts Section -->
<?php
  foreach ($import_scripts as $script) {
    echo '<script src="' . $script . '"></script>' . PHP_EOL;
  }
?><title>Demo</title>
    </head>
    <body>
      <p>Blog</p>

index.php

<?php
  $extra_scripts = ['file03.js'];
  include('header.php');
?>

Output (demo on 3v4l.org)

<!DOCTYPE html>
  <html>
    <head>
      <!-- Scripts Section -->
<script src="file01.js"></script>
<script src="file02.js"></script>
<script src="file03.js"></script>
<title>Demo</title>
    </head>
    <body>
      <p>Blog</p>
  • Related