How to know the predefined parameter in php functions? - php

If there is 2 parameter in php function how to know which parameter is kept in first and another second.
This is a php function array_search($needle,$array). This will search $needle in an array $array.
In array_slice($array, 2) slice is to be done in an array $array is first parameter.
In trim($string, 'abc') trim is to be done in string $string is a first parameter.
Is there any way to remember which parameter come first? I think we can remember function but remembering parameter also is not possible for all functions.
Thanks

Welcome to PHP ,
The likely most common complaint you get to hear about PHP is the
inconsistent and unclear naming of functions in the standard library,
as well as the equally inconsistent and unclear order of parameters.
Some typical examples:
// different naming conventions
strpos
str_replace
// totally unclear names
strcspn // STRing Complement SPaN
strpbrk // STRing Pointer BReaK
// inverted parameter order
strpos($haystack, $needle)
array_search($needle, $haystack)
so if you want to check (within your application and away from man pages)
as a work around to get around this, you may make use of Reflection collection in php :
for example:
function getFunctionInfo($functionName) {
$function = new ReflectionFunction($functionName);
return [
'name' => $function->getName(),
'parameters' => array_column($function->getParameters(), 'name'),
'numberOfParameters' => $function->getNumberOfParameters(),
'requiredParameters' => $function->getNumberOfRequiredParameters()
];
}
print_r(getFunctionInfo('explode'));
this will output:
Array (
[name] => explode
[parameters] => Array (
[0] => separator
[1] => str
[2] => limit
)
[numberOfParameters] => 3
[requiredParameters] => 2
)
and for live view: https://3v4l.org/T2Nad
the above quote had been quoted from : nikic.github.io

Related

Print result is different in the array function

I have a problem with the array PHP function, below is my first sample code:
$country = array(
"Holland" => "David",
"England" => "Holly"
);
print_r ($country);
This is the result Array ( [Holland] => David [England] => Holly )
I want to ask, is possible to make the array data become variables? For second example like below the sample code, I want to store the data in the variable $data the put inside the array.:
$data = '"Holland" => "David","England" => "Holly"';
$country = array($data);
print_r ($country);
But this result is shown me like this: Array ( [0] => "Holland" => "David","England" => "Holly" )
May I know these two conditions why the results are not the same? Actually, I want the two conditions can get the same results, which is Array ( [Holland] => David [England] => Holly ).
Hope someone can guide me on how to solve this problem. Thanks.
You can use the following Code.
<?php
$country = array(
"Holland" => "David",
"England" => "Holly"
);
foreach ($country as $index => $value)
{
$$index = $value;
}
?>
Now, Holland & England are two variables. You can use them using $Holland etc.
A syntax such as $$variable is called Variable Variable. Actually The inner $ resolves the a variable to a string, and the outer one resolves a variable by that string.
So there is this thing called
Destructuring
You can do it something like ["Holland" => $eolland, "England" => $england] = $country;
And now you have your array elements inside the variables.
Go read the article above if you want more information about this because it gets really useful (especially in unit tests usind data provders from my experience).
If you want to extract elements from an associative array such that the keys become variable names and values become the value of that variable you can use extract
extract($country);
To check what changed you can do
print_r(get_defined_vars());
Explanation on why the below does not work
$data = '"Holland" => "David","England" => "Holly"';
When you enclose the above in single quotes ' php would recognise it as a string. And php will parse a string as a string and not as an array.
Do note it is not enough to create a string with the same syntax as the code and expect php to parse it as code. The codes will work if you do this
$data = ["Holland" => "David","England" => "Holly"];
However, now $data itself is an array.
A simple copy of an array can be made by using
$data = $country;

Using str_replace() With Array Values Giving Unexpected Results

Using str_replace() to replace values in a couple paragraphs of text data, it seems to do so but in an odd order. The values to be replaced are in a hard-coded array while the replacements are in an array from a query provided by a custom function called DBConnect().
I used print_r() on both to verify that they are correct and they are: both have the same number of entries and are in the same order but the on-screen results are mismatched. I expected this to be straightforward and didn't think it needed any looping for this simple task as str_replace() itself usually handles that but did I miss something?
$replace = array('[MyLocation]','[CustLocation]','[MilesInc]','[ExtraDoc]');
$replacements = DBConnect($sqlPrices,"select",$siteDB);
$PageText = str_replace($replace,$replacements,$PageText);
and $replacements is:
Array
(
[0] => 25
[MyLocation] => 25
[1] => 45
[CustLocation] => 45
[2] => 10
[MilesInc] => 10
[3] => 10
[ExtraDoc] => 10
)
Once I saw what the $replacements array actually looked like, I was able to fix it by filtering out the numeric keys.
$replace = array('[MyLocation]','[CustLocation]','[MilesInc]','[ExtraDoc]');
$replacements = DBConnect($sqlPrices,"select",$siteDB);
foreach ($replacements as $key=>$value) :
if (!is_numeric($key)) $newArray[$key] = $value;
endforeach;
$PageText = str_replace($replace,$newArray,$PageText);
The former $replacements array, filtered to $newArray, looks like this:
Array
(
[MyLocation] => 25
[CustLocation] => 45
[MilesInc] => 10
[ExtraDoc] => 10
)
-- edited: Removed some non sense statements --
#DonP, what you are trying to do is possible.
In my opinion, the strtr() function could be more beneficial to you. All you need to make a few adjustments in your code like this ...
<?php
$replacements = DBConnect($sqlPrices,"select",$siteDB);
$PageText = strtr($PageText, [
'[MyLocation]' => $replacements['MyLocation'],
'[CustLocation]' => $replacements['CustLocation'],
'[MilesInc]' => $replacements['MilesInc'],
'[ExtraDoc]' => $replacements['ExtraDoc'],
]);
?>
This code is kinda verbose and requires writing repetitive strings. Once you understand the way it works, you can use some loops or array functions to refactor it. For example, you could use the following more compact version ...
<?php
// Reference fields.
$fields = ['MyLocation', 'CustLocation', 'MilesInc', 'ExtraDoc'];
// Creating the replacement pairs.
$replacementPairs = [];
foreach($fields as $field){
$replacementPairs["[{$field}]"] = $replacements[$field];
}
// Perform the replacements.
$PageText = strtr($PageText, $replacementPairs);
?>

PHP Count Number of Times A String Appears As A Value Inside An Array

So I looked around here for a bit but cant seem to get this right, so I am forced to make a new post. I gave it an effort! Don't hurt me.
Sample Array:
$ndata = Array
(
[ARMOR_HEAD] => Andariel's Visage
[ARMOR_TORSO] => Blackthorne's Surcoat
[ARMOR_FEET] => Illusory Boots
[ARMOR_HANDS] => Gauntlets of Akkhan
[ARMOR_SHOULDERS] => Pauldrons of Akkhan
[ARMOR_LEGS] => Blackthorne's Jousting Mail
[ARMOR_BRACERS] => Nemesis Bracers
[ARMOR_MAINHAND] => Gyrfalcon's Foote
[ARMOR_OFFHAND] => Jekangbord
[ARMOR_WAIST] => Blackthorne's Notched Belt
[ARMOR_RRING] => Ring of Royal Grandeur
[ARMOR_LRING] => Stone of Jordan
[ARMOR_NECK] => Kymbo's Gold
)
$count = count(preg_grep('Akkhan', $ndata));
print_r($count);
So this is only returns 1 instead of 2. I also tried array_search(), but that simply returns a the first found with its key. Or in_array but that is just boolean I guess.. Is there a better way to go about this?
The first parameter to preg_grep is not a string, it is a regular expression pattern represented as a string. Try this:
preg_grep('/Akkhan/i', $ndata)
For more information, see the documentation page for preg_grep.

PHP Convert variable names to lowercase?

I have an api listener script which takes in get parameters. But I seem to be having issues when users tend to pass mixed case variable names on the parameters.
For example:
http://mylistenerurl.com?paramName1=Hello&paramname2=World
I need my listener to be flixible in such a way that the variable names will be interpreted case-insensitively or rather still all in lower case like after I process the query string on some function, they are all returned as lower-cased variables:
extract(someFunction($_GET));
process($paramname1, $paramname2);
Can anybody shed some light on this?
*much appreciated. thanks!
This should do the trick:
$array_of_lower_case_strings = array_map( "strtolower", array( "This Will Be ALL lowercase.", ... ) );
So in your case:
$get_with_lowercase_keys = array_combine(
array_map( "strtolower", array_keys( $_GET ) ),
array_values( $_GET )
);
One thing I'll mention is you should be VERY careful with extract as it could be exploited to allow unexpected variables to be injected into your PHP.
Apply to your global variables ($_GET, $_POST) when necessary:
e.g. setLowerCaseVars($_GET); in your case
function setLowerCaseVars(&$global_var) {
foreach ($global_var as $key => &$value) {
if (!isset($global_var[strtolower($key)])) {
$global_var[strtolower($key)] = $value;
}
}
}
Edit: Note that I prefer this to using array_combine because it will not overwrite cases where the lower-case variable is already set.
PHP has had a native function (array_change_key_case()) for this task since version 4.2 to change the case of first level keys. To be perfectly explicit -- this function can be used to convert first level key to uppercase or lower case BUT this is not a recursive function so deeper keys will not be effected.
Code: (Demo)
parse_str('paramName1=Hello&paramname2=World&fOo[bAR][BanG]=boom', $_GET);
var_export($_GET);
echo "\n---\n";
$lower = array_change_key_case($_GET);
var_export($lower);
Output:
array (
'paramName1' => 'Hello',
'paramname2' => 'World',
'fOo' =>
array (
'bAR' =>
array (
'BanG' => 'boom',
),
),
)
---
array (
'paramname1' => 'Hello', # N changed to n
'paramname2' => 'World',
'foo' => # O changed to o
array (
'bAR' => # AR not changed because not a first level key
array (
'BanG' => 'boom', # B and G not changed because not a first level key
),
),
)

Parsing HTTP data into PHP variables

I have a reasonably large number of variables encoded in the form:
foo=bar&spam[eggs]=delicious&...
These are all in a single string (eg, $data = "foo=bar&spam[eggs]=delicious&..."). The variables are arbitrarily deeply nested -- easily four or five levels deep ("spam[eggs][bloody][vikings]=loud").
Is there an easy, reliable way to get a multi-dimensional PHP array from this? I assume PHP has a parser to do this, though I don't know if it's exposed for my use. Ideally, I could do something like:
// given $data == "foo=bar&spam[eggs]=delicious"
$arr = some_magical_function( $data );
/* arr = Array
(
[foo] => bar
[spam] => Array
(
[eggs] => delicious
)
)
*/
If your string is in URI params format, parse_str is the magic function you are looking for.
You might want to take a look at parse_str ; here's an example :
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
And, with your input :
$str = 'oo=bar&spam[eggs]=delicious&spam[eggs][bloody][vikings]=loud';
$output = array();
parse_str($str, $output);
var_dump($output);
You'll get this :
array
'oo' => string 'bar' (length=3)
'spam' =>
array
'eggs' =>
array
'bloody' =>
array
'vikings' => string 'loud' (length=4)
Which should be what you want ;-)
(notice the multi-level array ; and the fact that ths first spam[eggs] has been overriden by the second one, btw)
If your data comes from the request uri, use $_GET

Categories