URL not splitting into directories - php

I have a function that explodes a URL into directories. If I visit this script at example.com/test/directory, it should return test
function URLPart($part) {
if ($part > 0) {
$url = explode("/", $_SERVER['PHP_SELF']);
return $url[$part - 1];
} else {
return $_SERVER['PHP_SELF'];
}
}
URLPart(1);
Why is this not happening? I get nothing!

The $_SERVER['PHP_SELF'] variable contains an initial /, e.g. "/test/directory".
You have to ltrim($_SERVER['PHP_SELF'],'/'), before.
$url = explode("/", ltrim($_SERVER['PHP_SELF'], '/'));
or just :
return $url[$part];

There are two reasons you get nothing:
Because a function call doesn't print to screen -- echo does. You need to echo your return value.
#Syscall is correct that there is a leading / with $_SERVER['PHP_SELF'] so that is also throwing off your element targeting. 1 - 1 will have you accessing the 0 element explode()'s array. (I'm actually not sure why you were subtracting 1 from $part.)
While I am here I'll offer some additional advice.
$part is expected to be an integer, but let's force that to be true with intval().
!$part is used in the conditional to determine if the value is 0
I've extended your sample path string to illuminate my next point. I recommend adding $part+3 as the 3rd parameter of the explode() call so that the function doesn't have to do any unnecessary work. For this case, we are accessing element 2 of the array, so jamming the remainder of the path into element 3 is of no consequence. (see demo's output for how this works out)
Before attempting to access an array element by key, it is good practice to check that the key exists first -- to avoid a Notice. This is the reason for the !isset() condition.
++$part means add one to $part.
I prefer to write the early returns (failures) first in my codes, and put the successful output as the lowest return. And as I said earlier, echo the return value.
Code: (Demo)
function URLPart($part){
if(!$part=intval($part)){ // convert to integer and check if zero
return '/example.com/test/directory/foo/bar/what'; // $_SERVER['PHP_SELF']
}else{
$url = explode("/",'/example.com/test/directory/foo/bar/what',$part+3); // $_SERVER['PHP_SELF']
var_export($url);
echo "\n\n";
// when $part=1, offset 2 is desired
if(!isset($url[++$part])){ // if incremented $part is an invalid / non-existent offset
return '/example.com/test/directory/foo/bar/what'; // change this to your needs
}else{
return $url[$part];
}
}
}
echo URLPart(1); // you must echo the return value if you want it to be printed to screen
Output:
array (
0 => '',
1 => 'example.com',
2 => 'test',
3 => 'directory/foo/bar/what',
)
test

Related

Check if running script is in array

I'm trying to run a function but only on specific pages. I thought this would be fine...
$allowed_pages = array('/admin/update.php', '/admin/system.php', '/admin/install.php');
if($_SERVER['SCRIPT_NAME'] == $allowed_pages) {
myCoolFuntion();
}
...but it doesn't seem to work as expected and the myCoolFuntion() runs regardless of what page I am on.
If I echo $_SERVER['SCRIPT_NAME'] on any given page, I can see it does match up correctly (it matches a page specified in the array, for example, /admin/update.php as expected) and so I know the values in the array are in the correct format.
What am I doing wrong?
Based on the example provided, I can't see any way that myCoolFunction(); can ever execute.
$_SERVER['SCRIPT_NAME'] will never be equal to $allowed_pages because the first is a string and the second is an array.
Instead of the code as presented, use a function such as in_array to verify that the SCRIPT_NAME value is in the array:
$allowed_pages = array('/admin/update.php', '/admin/system.php', '/admin/install.php');
if (in_array($_SERVER['SCRIPT_NAME'], $allowed_pages)) {
myCoolFunction();
} else {
echo 'Not found in array';
}
in_array is defined thus:
Checks if a value exists in an array
More information about in_array is in the official docs.

why array_search function returns the key of 0 element when it is asked to search for a not included value?

Ok here I have an array named $fuitArray including some integers or strings (in this case [1,2,3,4,5,6,7,8,9,0]).
Everything works good when I try to set the $searchTarget to any of the elements inside the array, but when I try to search for anything else (in this case 'x') it returns 9 (the key for the 0 in the array).
It will also work fine if I remove 0 from array and search for a not-included element!
<?php
$fruitArray=[1,2,3,4,5,6,7,8,9,0];
$searchTarget='x';
$searchResult=array_search($searchTarget,$fruitArray);
if ($searchResult===false){
echo $searchTarget.' Not found'.'<br>';
} else{
echo $searchTarget.' Found # key#: '.$searchResult.'<br>';
}
echo '<br>';
while(current($fruitArray)!==false){
echo key($fruitArray).'. ';
echo current($fruitArray).'<br>';
next($fruitArray);
}
/>
i expected this to show
'x Not found'
instead of
'x Found # key#: 9'
array_search function doesn't check types of variables by default. It means strings and numbers will be compared by numbers rules.
For example, those rules might look like:
echo 0 == 'x' ? 'true' : 'false';
This example displays 'true' because it doesn't use strict comparison.
If you want to compare with the strict mode you should set strict parameter to true. For example:
$searchResult = array_search($searchTarget, $fruitArray, true);
You can get more information about the comparison in the documentation
You can do : $fruitArray=['1','2','3','4','5','6','7','8','9','0'];
Then it will return : x Not found

A character 1 after every value I get from the database using CodeIgniter [duplicate]

My print_r($view) function yields:
View Object
(
[viewArray:View:private] => Array
(
[title] => Projet JDelage
)
)
1 <--------------
What does the "1" at the end mean? The PHP manual isn't very clear on how to parse the output of print_r.
You probably have echo print_r($view). Remove the echo construct. And... what need do you have to parse its output? There are certainly much better ways to solve your problem.
print_r called with one argument (or with its second argument set to false), will echo the representation of its parameter to stdout. If it does this, it returns TRUE. Thus if you echo print_r($foo) you will print the contents of foo, followed by a string representation of the return value (which is 1).
When using print_r to return, than than output/print the value, pass the 2nd parameter which defines return as true.
echo print_r($view, true);
This is useful if you want to save the results to a variable or concatenate with another string.
$var = 'The array is: ' . print_r($view, true);

Return variable not working in PHP (i.e. no value returned!)

I prefer to program in Python language, but have to work in PHP for a specific web site app project.
In PHP I am trying to "return" a value from a function to the main program environment (to be used for subsequent calculations), but no matter what I try the value calculated in my function is not returning the value (but echoing from function works fine).
In Python I never had an issue with returning variables: i.e. all values returned from functions were available and accessible to the main program and/or other functions that called the function that produces the return value.
Can someone please tell me how I can solve this issue? I have been searching google and sites ike stackoverflow for the last 2 days with no success. I have many O'Reilly computer books including many on PHP where I have cross referenced my research and read everything I can about the RETURN function - it seems I am doing everything right and even specifically declaring the value to be returned. It is critical that I am able to return values and have access to those values in order to proceed with development on this project - else I am stuck if I cannot return values to be processed further!!
Here is the relevant code pieces:
// DECLARE FUNCTIONS
// FUNCTION
function Calculation_IsArray ($ArrayAny){
if (is_array($ArrayAny)) {
echo '<div>THIS VAR IS AN ARRAY</div>';
$Var_IsArray = TRUE;
return $Var_IsArray;
} else {
echo '<div>THIS VAR IS **NOT** AN ARRAY</div>';
}
}
After declaring the functions and doing some initial calculations to grab an array for checking, I call the above function as follows:
// CALL FUNCTION
Calculation_IsArray($ArrayOfValues);
I am expecting the program to call the function Calculation_IsArray() and pass it the array to be checked ($ArrayOfValues). You can see from the output below that the array is passed and checked and confirmed to be of array type, and both the FOREACH loop as well as the IF/ELSE conditions are working fine and echoing the correct output. However, the above code does not return any values as you can see the NULL values that are echoed when I check for returned values (i.e. that array that was checked) accessible from the main program after the "return".
And here are the results echoed to browser screen (output):
THIS VAR IS AN ARRAY
RETURNED ARRAY =
NULL
VALUE OF $Var_IsArray =
NULL
COUNT OF ARRAY KEY ELEMENTS = 2
ARRAY KEY ELEMENTS ARE NUMERIC
KEY = 0, VALUE = Array
COUNT OF ARRAY KEY ELEMENTS = 2
ARRAY KEY ELEMENTS ARE NUMERIC
KEY = 1, VALUE = Array
I have searched here at stackoverflow and found reports of similar problems (and I even tried to test those suggestions for solutions, e.g. placing return at various places in my function to test where it would work), but nothing is working, and this failure to return value is not logical according to what I have read that PHP returns values if expliciting told to RETURN.
Thank you very much for any help in this matter!
[After submission of the original question above]:
I am now trying to isolate my problem by creating a test script called TestReturn.php.
In that script I have placed the following code, but still there is no value returned!!
// DECLARE FUNCTIONS
// FUNCTION
function Calculation_IsArray ($ArrayAny){
if (is_array($ArrayAny)) {
echo '<div>THIS VAR IS AN ARRAY</div>';
$Var_IsArray = TRUE;
return $Var_IsArray;
} else {
echo '<div>THIS VAR IS **NOT** AN ARRAY</div>';
}
}
// BEGIN MAIN PROGRAM
$x = array(1, 2, 3, 4, 5, 6, 7);
Calculation_IsArray($x);
// COME BACK TO HERE AFTER THE FUNCTION RETURNS CALCULATED VALUE
echo '<div>HERE IS THE RETURNED VALUE AND VAR_DUMP BELOW:' . $Var_IsArray . '</div>';
var_dump($Var_IsArray);
And here is the output in HTML to browser tab/window/terminal:
THIS VAR IS AN ARRAY
HERE IS THE RETURNED VALUE AND VAR_DUMP BELOW:
NULL
"Captain, this does not compute!", i.e. this doesn't make sense to me why PHP is not returning my value that I specifically tell it to return to main program!
I have tried all possibilities of coding including:
return $variable;
return ($variable);
return() ; // i.e. I read somewhere that PHP by default returns the last calculated value in a function.
return ;
Why is PHP not returning my value/variable back to main program?
When you return something from a function, it doesn't make the variable itself available in the calling scope (i.e. outside the function). In other words, $Var_IsArray only exists inside the function.
Only the contents of the variable are returned, and you must use the result immediately where you call the function; e.g. store it for future reference, pass it to another function, or test it in a condition.
For example:
function foo()
{
$vals = ['red', 'green', 'blue'];
return $vals;
}
$somedata = foo();
In this example, $somedata will end up holding the array that previously was stored in $vals.
This is the standard behaviour for return statements (or equivalent functionality) in most programming languages. There are other ways to get variables out of a function, e.g. by using global variables. Generally, they're not good practice though.
I've used Python before too, and I don't think it's any different (unless I've missed a major language feature). You might want to double-check that your Python code is doing what you think it's doing, otherwise you could end up with some nasty bugs in future.
you could simplify the function to the following so it always returns something ( true,false )
function Calculation_IsArray( $ArrayAny ){
echo is_array($ArrayAny) ? '<div>THIS VAR IS AN ARRAY</div>' : '<div>THIS VAR IS **NOT** AN ARRAY</div>';
return is_array($ArrayAny);
}
Hope this will help:
// FUNCTION
function Calculation_IsArray ($ArrayAny){
if (is_array($ArrayAny)) {
echo '<div>THIS VAR IS AN ARRAY</div>';
return true;
} else {
echo '<div>THIS VAR IS **NOT** AN ARRAY</div>';
return false;
}
}
$array = array(1, 1, 1);
if ( Calculation_IsArray($array) ){
print_r( $array );
}
<?php
// DECLARE FUNCTIONS
// FUNCTION
function Calculation_IsArray ($ArrayAny){
if (is_array($ArrayAny)) {
echo '<div>THIS VAR IS AN ARRAY</div>';
//$Var_IsArray = TRUE;
return true;
} else {
echo '<div>THIS VAR IS **NOT** AN ARRAY</div>';
}
}
// BEGIN MAIN PROGRAM
$x = array(1, 2, 3, 4, 5, 6, 7);
$status = Calculation_IsArray($x);
if($status == true){
// COME BACK TO HERE AFTER THE FUNCTION RETURNS CALCULATED VALUE
echo '<div>HERE IS THE RETURNED VALUE AND VAR_DUMP BELOW:<br />' . print_r($x) . '</div>';
var_dump($x);
}
ok, so while Peter Bloomfield was responding and writing his CORRECT answer, I was hacking away myself and trying different things and remembered that what I also do in Python is make a variable equal to the function call!! I tried that and now it is returning fine anything I do with that function, thank GOD!!
Here is the updated code in main program now that received ok the returned value (it is no longer returning just NULL):
// BEGIN MAIN PROGRAM
$x = array(1, 2, 3, 4, 5, 6, 7);
$ResultOfCalculation = Calculation_IsArray($x);
// COME BACK TO HERE AFTER THE FUNCTION RETURNS CALCULATED VALUE
echo '<div>HERE IS THE RETURNED VALUE AND VAR_DUMP BELOW:' . $ResultOfCalculation . '</div>';
var_dump($ResultOfCalculation);

What is wrong with this loop code

So i wrote some code for making seo-friendly urls. These functions first make a seo-friendly slug and then if the slug already exists is the DB(in this case array) then they add a number with a dash next to it. if that also exists then they just +1 the number and then checks again and again...
eg. if i pass "title url" to the function. First it will convert it to "title-url" and if "title-url" already exists then it will add a number like "title-url-1" if it exists as well then it will +1 the number like "title-url-2" and then "title-url-3" and so on...
this is the code:
// CONVERTS STRING TO URL SLUG
function str_to_slug($str){
$str = strtolower(trim($str));
$str = preg_replace('/[^a-z0-9-]/', '-', $str);
$str = preg_replace('/-+/', "-", $str);
return $str;
}
// RETURN SLUG URL
function slug($title){
$ori_url = str_to_slug($title);
if( does_slug_exists($ori_url) ){
return loop_slug_number($ori_url, 1);
}
else{
return $ori_url;
}
}
// ADD NUMBER
function loop_slug_number($slug, $number){
if( does_slug_exists($slug.'-'.$number) ){
loop_slug_number($slug, $number++);
exit;
}
else{
return $slug.'-'.$number;
}
}
// CHECKS WHEATHER THE SLUG EXISTS IN THE DB
function does_slug_exists($slug){
$array = array("title", "title-0", "title-1", "title-2");
return (in_array($slug, $array)) ? true : false;
}
i think everything should work fine. but when i echo slug("title"); i'm getting
Fatal error: Maximum function nesting level of '100' reached, aborting!
error line number is in the function does_slug_exists() on the 'return' line.
(the array is just for example i will use db validation.)
also if i replace the array with:
$array = array("title", "title-0", "title-2", "title-3");
then i get title-1 back.
Where is the mistake?
Ignoring any comments about the code quality, the issue here is the post-increment of the $number variable. You can replace with:
return loop_slug_number($slug, ++$number);
However, I suggest that the entire function should be rewritten as a while loop as opposed to a pseudo-recursive function. In addition, it looks like a DB query is made upon each call of does_slug_exists(); I suggest you refactor this to make the query once and store the returned result set. Have a look at this example.
// ADD NUMBER
function loop_slug_number($slug, $number){
if( does_slug_exists($slug.'-'.$number) ){ loop_slug_number($slug, $number++); exit; }else{ return $slug.'-'.$number; }
}
This is really awful code. Instead of looping, use a while loop. Start the number at 0 and while the slug exists, increment the number.
I'm not sure about PHP, but in C you should do a ++number instead. The idea is that the number gets incremented after the function was called if you do a number++ and before if you do ++number.
.. the joys of increment/decrement operators...

Categories