简体   繁体   中英

Get value from inside PHP array and display it when href is selected

I have the following php code below. I would like that when the user hits the Delete Now button - the picture value is displayed. Regardless of which any button I select the picture05 gets displayed.

I may have a problem getting the selected value from the foreach to the echo code below

<?php
$pic_names = array (
    '01' => 'picture01',
    '02' => 'picture02',
    '03' => 'picture03',
    '04' => 'picture04',
    '05' => 'picture05',
);

foreach($pic_names as $pic_key => $pic_value){
echo '<a href="?delete=';
echo $pic_value;
echo '">Delete Now!</a><br/>';
}

//Delete Images
if(isset($_GET['delete'])){
echo $pic_value;
}
?>

Try this:

foreach($pic_names as $pic_key => $pic_value){
     echo '<a href="?delete='.$pic_value.'">Delete Now!</a><br/>';
}

In you code you make checking GET but echo another variable, try this:

if(isset($_GET['delete'])){
   echo $_GET['delete'];
} 

$pic_value contains the value of the last iteration of your foreach loop. use the value of $_GET['delete'] .

if(isset($_GET['delete'])){
  echo $_GET['delete'];
}

Try some thing like this

foreach($pic_names as $pic_key => $pic_value){
$href = "";
$href = '<a href="?delete=';
$href.= $pic_value;
$href.= '">Delete Now!</a><br/>';
echo $href;
}

And then try

if(isset($_GET['delete'])){
  echo $_GET['delete'];
}

Your loop is fine, you just print the wrong variable. Try this: (I recommend you to expose keys rather than names)

$pic_names = array (
    '01' => 'picture01',
    '02' => 'picture02',
    '03' => 'picture03',
    '04' => 'picture04',
    '05' => 'picture05',
);

foreach($pic_names as $pic_key => $pic_value){
    print '<a href="?delete='.$pic_key.'">Delete Now!</a><br/>';
}

//Delete Images
if(isset($_GET['delete'])){
    print $pic_names[$_GET['delete']];
}

You could drop your photo "keys" and use the natural keys from the array. Then show the image if $_GET['delete'] is defined. If not show your delete links.

<?php
    $pic_names = array(
        'picture01', 
        'picture02', 
        'picture03', 
        'picture04',
        'picture05',
    );

    if(isset($_GET['delete']) {
        $imgPath = "define/your/path/here/";
        echo '<img src="' . $imgPath . $pic_names[$_GET['delete']] . '">';
    } else {
        foreach($pic_names as $pic_key => $pic_value){
            echo '<a href="?delete=' . $key . '">Delete: ' . $pic_value . '</a><br />';
        }
    }
    ?>

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