使用变量调用数组项


Call an array entry with a variable

是否可以用变量调用数组项?

$files = array('img/1.jpg','img/2.jpg','img/3.jpg');
$slot=0;
$fullpath = 'img/4.jpg'; //In the original Programm this path is generated
$files[$slot] = $fullpath;

当我尝试这个代码时,它不起作用。

我确信它运行良好。

<?php
$files = array('img/1.jpg','img/2.jpg','img/3.jpg');
$slot=0;
$files[$slot] = '';
array_push($files ,$fullpath);
?>
$files = array('img/1.jpg','img/2.jpg','img/3.jpg');
$slot=0;
$fullpath = $files[$slot];

并且,添加新值:

$new_value = 'img/4.jpg';
$files[] = $new_value; //or $files[] = 'img/4.jpg';

替换$files〔$slot〕

$fullpath = 'img/4.jpg';
$files[$slot] = $fullpath;

试试这个

$files = array('img/1.jpg','img/2.jpg','img/3.jpg');
$slot = 0;
if(isset($files[$slot]))
{
   $fullpath = realpath($files[$slot]);
}

为赋值切换变量。

$files[$slot] = $fullpath; to  $fullpath = $files[$slot];

因为您正在为$fullpath变量赋值。