Hello I know all about http://www.php.net/manual/en/function.http-build-query.php to do this however I have a little problem.
It "handly" turns boolean values into ones and zeros for me. I am building a little PHP wrapper for the Stack Overflow api and parsing an option array and then sending this onto the api breaks things..(doesn't like 1 for true).
What I would like is a simple function to turn a single dimensional array into a query string but turning true/false into string values of true/false.
Anyone know of anything that can do this before I start re-inventing the wheel
I don't know of anything offhand. What I'd recommend is first iterating through the array and covert booleans to strings, then call http_build_query
E.g.
foreach($options_array as $key=>$value) :
if(is_bool($value) ){
$options_array[$key] = ($value) ? 'true' : 'false';
}
endforeach;
$options_string=http_build_query($options_array);
Try passing http_build_query true and false as strings instead of booleans. You may get different results.
If you just need to convert your true/false to "true"/"false":
function aw_tostring (&$value,&$key) {
if ($value === true) {
$value = 'true';
}
else if ($value === false) {
$value = 'false';
}
}
array_walk($http_query,'aw_tostring');
// ... follow with your http_build_query() call
Loop through each variable of the query string ($qs) and if bool true or false, then change value to string.
foreach($qs as $key=>$q) {
if($q === true) $qs[$key] = 'true';
elseif($q === false) $qs[$key] = 'false';
}
Then you can use the http_build_query()
have a look at my wheel:
function buildSoQuery(array $array) {
$parts = array();
foreach ($array as $key => $value) {
$parts[] = urlencode($key).'='.(is_bool($value)?($value?'true':'false'):urlencode($value));
}
return implode('&', $parts);
}
Related
I have designed below code where i am using explode to explode below data,
"10.74.10.1", "10.75.10.132"
however i getting below error
"explode() expects parameter 2 to be string, array given in line.."
Can someone please suggest whats wrong in my code.
This is my full code:
public function pagesviewlogsAction()
{
// Checks authorization
$this->acl->doCheck($this);
-- language: lang-html --> // Validates request
$requestObj = new PagesviewlogEventRequest();
$requestObj->userid = (Utils::validatePattern(Utils::REGEXP_SECLOGS_USERID, (($json->userid) ?? FALSE) )) ? $json->userid:NULL;
$requestObj->clientip = array();
//if (isset($json->clientip) && $json->clientip != '' && $json->clientip != NULL) {
if (isset($json->clientip) && is_string($json->clientip)){
$tmp = explode(',', $json->clientip);
foreach ($tmp as $key => $ipValue) {
$requestObj->clientip[] = (Utils::validatePattern(Utils::REGEXP_SECLOGS_IP, ((trim($ipValue)) ?? FALSE) )) ? trim($ipValue):NULL;
}
}
}
foreach (get_object_vars($requestObj) as $key => $value) {
switch ($key) {
case 'clientip':
// ...
break;
default:
// Other cases
if ($value === FALSE) {
return new JsonModel([
'status' => 'FAILED',
'errorField' => $key,
'message'=> 'Parameters "' . $key . '" is missing or invalid.',
'data' => NULL
]);
}
break;
}
}
}
}
You condition :
if (isset($json->clientip) && $json->clientip != '' && $json->clientip != NULL)
can return true with an array.
better use something like this :
if (isset($json->clientip) && is_string($json->clientip))
The function explode() will convert a string to an array using a given separator, in your case ","
Since $json->clientip is already an array, the simple(not the best) solution is to change the code to:
$requestObj->clientip = array();
if (is_array($json->clientip)) {
foreach ($json->clientip as $key => $ipValue) {
$requestObj->clientip[] = (Utils::validatePattern(Utils::REGEXP_SECLOGS_IP, ((trim($ipValue)) ?? FALSE) )) ? trim($ipValue):NULL;
}
} else {
//handle the other option here. like string or object
}
and it depends on the source of the $json->clientip to make sure you have the correct approach in case you don't receive an array.
Exactly as it's telling you,
"10.74.10.1", "10.75.10.132" is an array. Explode requires a string because it creates an array based on the seperator ,
Try a var_dump() on your $json->clientip and see what it looks like, you may have to re-work your code a bit here.
Can I propose a possibility? I would check for both possible cases. If array execute one way, if string execute your explode.
if (!isset($json->clientip)) {
// thow exception or return call
}
$requestObj->clientip = [];
if (is_array($json->clientip)) {
array_walk($json->clientip, function($ipValue) use(&$requestObj) {
$ipValue = trim($ipValue);
$requestObj->clientip[] = (Utils::validatePattern(Utils::REGEXP_SECLOGS_IP, (($ipValue) ?? FALSE) )) ? $ipValue:NULL;
});
} else if (is_string($json->clientip)) {
// execute your explode
}
Also I would advice to check on Marshallers to help you parse logic in your code to tidy it up more instead of leaving it all into the same place. So your Utils::validatePattern could be a Marshaller in my opinion
I want to check if a string contains two specific words.
For example:
I need to check if the string contains "MAN" & "WAN" in a sentence like "MAN live in WAN" and returns true else false.
What I've tried is looping string function in a conditional way:-
<?php
$data = array("MAN","WAN");
$checkExists = $this->checkInSentence($data);
function checkInSentence( $data ){
$response = TRUE;
foreach ($data as $value) {
if (strpos($string, $word) === FALSE) {
return FALSE;
}
}
return $response;
}
?>
Is it the right method or do I've to change it? How to implement this any suggestions or idea will be highly appreciated.
Note: data array may contain more than two words may be. I just need check whether a set of words are exists in a paragraph or sentence.
Thanks in advance !
It's alsmost good. You need to make it set the response to false if a word is not included. Right now it'll always give true.
if (strpos($string, $word) === FALSE) {
$response = FALSE;
}
Try this:
preg_match_all("(".preg_quote($string1).".*?".preg_quote($string2).")s",$data,$matches);
This also should work!
$count = count($data);
$i = 0;
foreach ($data as $value) {
if (strpos($string, $value) === FALSE) {
#$response = TRUE; // This is subject to change so not reliable
$i++;
}
}
if($i<$data)
response = FALSE;
I am in the middle of building a cache layer for the Redis DB to my application and I have come to the point where's it's about to take care of arrays.
I wonder if there's any good (high performance!) way of controlling an string to be serialized or not with PHP?
Thanks a lot!
$array = #unserialize($string);
if ($array === false && $string !== 'b:0;') {
// woops, that didn't appear to be anything serialized
}
The $string !== 'b:0;' checks to see if the serialized string may have been the value false. If this check is important to you you may want to trim the serialized string or otherwise preprocess it to make sure this works.
For those looking for alternative, this code worked for me as helper function for Laravel framework and then you can call it anywhere.
if(!function_exists('isSerialized')){
function isSerialized($string){
$tempString = '';
$array = #unserialize($string);
if(is_array($array)){
foreach ($array as $k=>$i){
//do something with data
$tempString .= $k . $i['something'];
}
} else {
$tempString = $string;
}
return $itemString;
}
}
Is it possible to use array_map() to test values of an array? I want to make sure that all elements of an array are numeric.
I've tried both
$arrays = array(
array(0,1,2,3 )
, array ( 0,1, "a", 5 )
);
foreach ( $arrays as $arr ) {
if ( array_map("is_numeric", $arr) === FALSE ) {
echo "FALSE\n";
} else {
echo "TRUE\n";
}
}
and
$arrays = array(
array(0,1,2,3 )
, array ( 0,1, "a", 5 )
);
foreach ( $arrays as $arr ) {
if ( ( array_map("is_numeric", $arr) ) === FALSE ) {
echo "FALSE\n";
} else {
echo "TRUE\n";
}
}
And for both I get
TRUE
TRUE
Can this be done? If so, what am I doing wrong?
Note: I am aware that I can get my desired functionality from a foreach loop.
array_map returns an array. So it will always be considered 'true'. Now, if you array_search for FALSE, you might be able to get the desire effects.
From the PHP.net Page
array_map() returns an array containing all the elements of
arr1 after applying the callback function to each one.
This means that currently you have an array that contains true or false for each element. You would need to use array_search(false,$array) to find out if there are any false values.
I'm usually a big advocate of array_map(), array_filter(), etc., but in this case foreach() is going to be the best choice. The reason is that with array_map() and others it will go through the entire array no matter what. But for your purposes you only need to go through the array until you run into a value for which is_numeric() returns false, and as far as I know there's no way in PHP to break out of those methods.
In other words, if you have 1,000 items in your array and the 5th one isn't numeric, using array_map() will still check the remaining 995 values even though you already know the array doesn't pass your test. But if you use a foreach() instead and have it break on is_numeric() == false, then you'll only need to check those first five elements.
You could use filter, but it ends up with a horrible bit of code
$isAllNumeric = count(array_filter($arr, "is_numeric")) === count($arr)
Using a custom function makes it a bit better, but still not perfect
$isAllNumeric = count(array_filter($arr, function($x){return !is_numeric($x);})) === 0
But if you were using custom functions array_reduce would work, but it still has some failings.
$isAllNumeric = array_reduce($arr,
function($x, $y){ return $x && is_numeric($y); },
true);
The failings are that it won't break when it has found what it wants, so the functional suggestions above are not very efficient. You would need to write a function like this:
function array_find(array $array, $callback){
foreach ($array as $x){ //using iteration as PHP fails at recursion
if ( call_user_func($callback, array($x)) ){
return $x;
}
}
return false;
}
And use it like so
$isAllNumeric = array_find($arr, function($x){return !is_numeric($x);})) !== false;
i have two tiny but extremely useful functions in my "standard library"
function any($ary, $func) {
foreach($ary as $val)
if(call_user_func($func, $val)) return true;
return false;
}
function all($ary, $func) {
foreach($ary as $val)
if(!call_user_func($func, $val)) return false;
return true;
}
in your example
foreach ( $arrays as $arr )
echo all($arr, 'is_numeric') ? "ok" : "not ok";
A more elegant approach IMHO:
foreach ($arrays as $array)
{
if (array_product(array_map('is_numeric', $array)) == true)
{
echo "TRUE\n";
}
else
{
echo "FALSE\n";
}
}
This will return true if all the values are numeric and false if any of the values is not numeric.
I'm working on a program that uses PHP's internal array pointers to iterate along a multidimensional array. I need to get an element from the current row, and I've been doing it like so:
$arr[key($arr)]['item']
However, I'd much prefer to use something like:
current($arr)['item'] // invalid syntax
I'm hoping there's a function out there that I've missed in my scan of the documentation that would enable me to access the element like so:
getvalue(current($arr), 'item')
or
current($arr)->getvalue('item')
Any suggestions?
I very much doubt there is such a function, but it's trivial to write
function getvalue($array, $key)
{
return $array[$key];
}
Edit: As of PHP 5.4, you can index array elements directly from function expressions, current($arr)['item'].
Have you tried using one of the iterator classes yet? There might be something in there that does exactly what you want. If not, you can likely get what you want by extending the ArrayObject class.
This function might be a bit lenghty but I use it all the time, specially in scenarious like:
if (array_key_exists('user', $_SESSION) === true)
{
if (array_key_exists('level', $_SESSION['user']) === true)
{
$value = $_SESSION['user']['level'];
}
else
{
$value = 'DEFAULT VALUE IF NOT EXISTS';
}
}
else
{
$value = 'DEFAULT VALUE IF NOT EXISTS';
}
Turns to this:
Value($_SESSION, array('user', 'level'), 'DEFAULT VALUE IF NOT EXISTS');
Here is the function:
function Value($array, $key = 0, $default = false)
{
if (is_array($array) === true)
{
if (is_array($key) === true)
{
foreach ($key as $value)
{
if (array_key_exists($value, $array) === true)
{
$array = $array[$value];
}
else
{
return $default;
}
}
return $array;
}
else if (array_key_exists($key, $array) === true)
{
return $array[$key];
}
}
return $default;
}
PS: You can also use unidimensional arrays, like this:
Value($_SERVER, 'REQUEST_METHOD', 'DEFAULT VALUE IF NOT EXISTS');
If this does not work, how is your multidimensional array composed? A var_dump() might help.
$subkey = 'B';
$arr = array(
$subkey => array(
'AB' => 'A1',
'AC' => 'A2'
)
);
echo current($arr[$subkey]);
next($arr[$subkey]);
echo current($arr[$subkey]);
I often use
foreach ($arr as $key=>$val) {
$val['item'] /*$val is the value of the array*/
$key /*$key is the key used */
}
instead of
next($arr)/current($arr)