How to convert getimagesize() result to variables?

白昼怎懂夜的黑 提交于 2019-12-25 02:29:51

问题


Is there a function that gives me back all results of getimagesize() as associative array or single variables with self-explaining names? I know that I could do it with a foreach loop, but there must be a better way.

Result of var_dump(getimagesize('foo.png'));:

array
  0 => int 500
  1 => int 250
  2 => int 3
  3 => string 'width="500" height="250"' (length=24)
  'bits' => int 8
  'mime' => string 'image/png' (length=9)

list()

Function list does not work because of its behavior:

Note: list() only works on numerical arrays and assumes the numerical indices start at 0.

extract()

Function extract could work if you use a prefix:

Note that prefix is only required if flags is EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS. If the prefixed result is not a valid variable name, it is not imported into the symbol table. Prefixes are automatically separated from the array key by an underscore character.

But then you would have variables like <prefix>_0 and <prefix>_1 and so on. That is not self-explaining.


回答1:


Only way I found is to use array_values() to get a pure numerical indexed array and use it with list().

Solution for single variables:

list(
      $width, 
      $height, 
      $mimeType, 
      $htmlAttr, 
      $bits, 
      $mime
) = array_values(getimagesize('foo.png'));

Solution for associative array:

list(
     $imgInfo['width'], 
     $imgInfo['height'], 
     $imgInfo['mimeType'], 
     $imgInfo['htmlAttr'], 
     $imgInfo['bits'], 
     $imgInfo['mime']
) = array_values(getimagesize('foo.png'));


来源:https://stackoverflow.com/questions/23562608/how-to-convert-getimagesize-result-to-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!