1、合并两个数组有几种方式, 试比较它们的异同
方式:
1)array_merge()
2) “+”
3)array_merge_recursive
异同:
array_merge简单的合并数组
array_merge_recursive合并两个数组,如果数组中有完全一样的数据,将它们递归合并
array_combine和”+”, 合并两个数组,前者的值作为新数组的键
2、PHP的is_writeable()函数存在Bug, 无法准确判断一个目录/文件是否可写,请写一个函数来判断目录/文件是否绝对可写
Bug存在两个方面:
1、在windows中,当文件有只读属性时,is_writeable()函数才返回false, 当返回true时,该文件不一定是可写的。如果是目录,在目录中新建文件并通过打开文件来判断;如果是文件,可以通过打开文件(fopen),来测试文件是否可写。
2、在Unix中,当php配置文件中开启safe_mode时(safe_mode=on), is_writeable()同样不可用。读取配置文件是否safe_mode是否开启
/**
* Tests for file writability
*
* is_writable() returns TRUE on Windows servers when you really can't write to
* the file, based on the read-only attribute. is_writable() is also unreliable
* on Unix servers if safe_mode is on.
*
* @access private
* @return void
*/
if ( ! function_exists('is_really_writable'))
{
function is_really_writable($file){
// If we're on a Unix server with safe_mode off we call is_writable
if (DIRECTORY_SEPARATOR == '/' AND @ini_get("safe_mode") == FALSE){
return is_writable($file);
}
// For windows servers and safe_mode "on" installations we'll actually
// write a file then read it. Bah...
if (is_dir($file)){
$file = rtrim($file, '/').'/'.md5(mt_rand(1,100).mt_rand(1,100));
if (($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE){
return FALSE;
}
fclose($fp);
@chmod($file, DIR_WRITE_MODE);
@unlink($file);
return TRUE;
} elseif ( ! is_file($file) OR ($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE) {
return FALSE;
}
fclose($fp);
return TRUE;
}
}
3. PHP的垃圾收集机制是怎样的?
php可以自动进行内存管理,清除不再需要的对象。php使用了引用计数(reference counting)这种单纯的垃圾回收(garbage collection)机制。
每个对象都内含一个引用计数器,每个reference连接到对象,计数器加1。当reference离开生存空间或被设为NULL, 计数器减1. 当某个对象的引用计数器为零时,php知道你将不再使用这个对象,释放其所占的内存空间。
4. 写一个函数,尽可能高效的,从一个标准url里取出文件的扩展名?
例如: http://www.startphp.cn/abc/de/fg.php?id=1需要取出php或.php
<?php
//方案一
function getExt1($url) {
$arr = parse_url($url);
/**
*
* Array(
* [schema] => http
* [host] => www.startphp.cn
* [path] => /abc/de/fg.php
* [query]=> id=1
* )
**/
$file = basename($arr['path']);
$ext = explode(".", $file)
return $ext[count($ext)-1];
}
//方案二
function getExt2($url) {
$url = basename($url);
$pos1 = strpos($url, '.');
$pos2 = strpos($url, "?");
if (strstr($url, "?")) {
return substr($url, $pos1+1, $pos2-$pos1-1);
} else {
return substr($url, $pos1);
}
}
$path = "http://www.startphp.cn/abc/de/fg.php?id=1"
echo getExt1($path);
echo "<br/>";
echo getExt2($path);