有没有更简单的方法来更改单个数组值?
我想要做的是将 $names
数组值默认为其并行 $urls
值(如果 $_POST[]
值为 < code>$names 为空。 (这是基于空的 $_POST[]
将返回空的假设,如果我错了,请纠正我)。
这是我的代码:
$urls = array(1 => $_POST['url_1'], 2 => ['url_2'], 3 => $_POST['url_3'], 4 => $_POST['url_4'], 5 => $_POST['url_5']);
$names = array(1 => $_POST['name_1'], 2 => ['name_2'], 3 => $_POST['name_3'], 4 => $_POST['name_4'], 5 => $_POST['name_5']);
if(empty($names[1])) { $names[1] = $_POST['url_1']; }
if(empty($names[2])) { $names[2] = $_POST['url_2']; }
if(empty($names[3])) { $names[3] = $_POST['url_3']; }
if(empty($names[4])) { $names[4] = $_POST['url_4']; }
if(empty($names[5])) { $names[5] = $_POST['url_5']; }
我考虑过使用 foreach()
循环,但我真的不明白它是如何工作的,因为每个单独的数组值例如 $names[1]
如果为空,则必须设置为 $urls[1]
。
任何建议、评论或其他信息将不胜感激:)!
What I'm trying to do is default the $names
array value to it's parallel $urls
value if a $_POST[]
value of $names
is empty. (This is based on the assumption that an empty $_POST[]
will return empty, someone please correct me if I'm wrong).
Here's my code:
$urls = array(1 => $_POST['url_1'], 2 => ['url_2'], 3 => $_POST['url_3'], 4 => $_POST['url_4'], 5 => $_POST['url_5']);
$names = array(1 => $_POST['name_1'], 2 => ['name_2'], 3 => $_POST['name_3'], 4 => $_POST['name_4'], 5 => $_POST['name_5']);
if(empty($names[1])) { $names[1] = $_POST['url_1']; }
if(empty($names[2])) { $names[2] = $_POST['url_2']; }
if(empty($names[3])) { $names[3] = $_POST['url_3']; }
if(empty($names[4])) { $names[4] = $_POST['url_4']; }
if(empty($names[5])) { $names[5] = $_POST['url_5']; }
I thought about using a foreach()
loop, but I don't really see how that would work, as each individual array value e.g. $names[1]
would have to be set to $urls[1]
if empty.
Any advice, comments or other information would be very much appreciated :)!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
但请记住,您还需要检查
$_POST['url_' 是否。 $i']
也存在,需要额外的isset()
检查But keep in mind that you also need to check if
$_POST['url_' . $i']
exists too with additionalisset()
check