简体   繁体   中英

Printing array output in PHP in a readable format

I'm trying to print multiple values user has selected on form submit. However with following what I'm seeing is only the last element printed irrespective whether it is selected or not.

Note that the print on the screen I'm looking at is a print that a layman can understand!

    <?php
    if(isset($_POST['submit'])) {
    //I'm trying to show the user these are the values you've selected
    print_r($option['name']);
    }
    ?>

    <form method="post" action="<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]);?>">
        <td class="container">
            <select multiple name="mercha_A[]" class="selectpicker form-control" title="Merchandiser type">
      <?php foreach ($options as $option) { ?>
            <option value="<?php echo $option['value']; ?>" <?php echo (isset($_POST[ 'mercha_A']) && in_array($option[ 'value'], $_POST[ 'mercha_A'])) ? ' selected="selected"' : ''; ?>>
                <?php echo $option['name']; ?>
            </option>
    <?php } ?>
    </select>
        </td>
        <td><button type="submit" name="submit">Submit</button></td>
    </form>

Anyone needs a coffee on my account?

wrap your print_r in <pre> Tags

echo "<pre>";
print_r($option['name']);
echo "</pre>;

I think you meant to print

$_POST['mercha_A'];

Otherwise, $option['name'] is completely undefined in your case, but even if you put the print_r() at the end of the script, it would only be the name of the last option in $options .

In order to make print_r() readable, you can View Source (Ctrl+U) in your browser, or wrap it in <pre></pre> tags.

echo "<pre>";
print_r($_POST['mercha_A']); // you have to print the name attribute not option
echo "</pre>;

Using extbase debugger from TYPO3.

Check it out it's insane :) https://github.com/TYPO3/TYPO3.CMS/blob/master/typo3/sysext/extbase/Classes/Utility/DebuggerUtility.php

It helps you to debug arrays and object in a readable way

DebuggerUtility::var_dump($array)

depending on your situation, you could use either of these, I think the last will best suite those who don't have a programming background. Because, I think JSON is a human readable format.

Method 1:

echo '<pre>'; print_r($_POST['mercha_A']); echo '</pre>';

Method 2:

echo json_encode($_POST['mercha_A']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM