PHP中将数组的第一个元素转换为字符串 [英] Convert the first element of an array to a string in PHP

查看:60
本文介绍了PHP中将数组的第一个元素转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 PHP 数组,想将其转换为字符串.

I have a PHP array and want to convert it to a string.

我知道我可以使用 joinimplode,但就我而言,数组只有一项.为什么我必须在只有一项的数组中使用组合值?

I know I can use join or implode, but in my case array has only one item. Why do I have to use combine values in an array with only one item?

这个数组是我的 PHP 函数的输出,它返回一个数组:

This array is the output of my PHP function which returns an array:

Array(18 => 'Something');

如何将其转换为字符串?

How do I convert this to a string?

推荐答案

有没有其他方法可以将该数组转换为字符串?

Is there any other way to convert that array into string ?

如果我没看错,您不想将数组转换为字符串,而是想获取数组唯一元素的值.

You don't want to convert the array to a string, you want to get the value of the array's sole element, if I read it correctly.

<?php
  $foo = array( 18 => 'Something' );
  $value = array_shift( $foo );
  echo $value; // 'Something'.

?>

使用 array_shift 你不必担心索引.

Using array_shift you don't have to worry about the index.

EDIT:请注意,array_shift 不是唯一返回单个值的函数.array_pop()、current()、end()、reset(),它们都将返回单个元素.所有发布的解决方案都有效.但是使用数组移位,您可以确定您只会获得数组的第一个值,即使有多个值也是如此.

EDIT: Mind you, array_shift is not the only function that will return a single value. array_pop( ), current( ), end( ), reset( ), they will all return that one single element. All of the posted solutions work. Using array shift though, you can be sure that you'll only ever get the first value of the array, even when there are multiple.

这篇关于PHP中将数组的第一个元素转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆