note 56945 added to function.array-shift

From: Date: Tue, 20 Sep 2005 02:57:30 +0000
Subject: note 56945 added to function.array-shift
Groups: php.notes 
Request: Send a blank email to php-notes+get-95444@lists.php.net to get a copy of this message
<?php //---------------------------------------------------------- // The combination of array_shift/array_unshift // greatly simplified a function I created for // generating relative paths. Before I found them // the algorithm was really squirrely, with multiple // if tests, length calculations, nested loops, etc. // Great functions. //---------------------------------------------------------- function create_relative_path($inSourcePath, $inRefPath) { // break strings at slashes $s_parts = explode('/', $inSourcePath); $r_parts = explode('/', $inRefPath); // delete items up to the first non-equal part while ($s_parts[0] === $r_parts[0]) { array_shift($s_parts); array_shift($r_parts); } // add wild card to r_parts for each remaining // item of s_parts while ($s_parts[0]) { array_unshift($r_parts, '..'); array_shift($s_parts); } return implode('/', $r_parts); } //---------------------------------------------------------- // Example: // Given a source path $sp generates the relative // location of $rp. $sp could be assigned using // $_SERVER['PHP_SELF'] but it's hardcoded for // the example. //---------------------------------------------------------- $sp = '/WebServer/Documents/MyBigProject/php/project_script.php'; $rp = '/WebServer/Documents/MyLibraries/lib_script.php'; // plugging them into the function $rel_path = create_relative_path($sp, $rp); // yeilds '../../../MyLibraries/lib_script.php' // and it could be used like include_once(create_relative_path($_SERVER['PHP_SELF'], $rp)); ---- Manual Page -- http://www.php.net/manual/en/function.array-shift.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+56945 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+56945&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+56945&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+56945&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+56945&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+56945&report=yes&reason=non-english Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+56945&report=yes&reason=already+in+docs Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+56945&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+56945&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#95444) next »