First of all: Yes i did check other answers but they sadly didn't do the trick.
So i'm currently working on a script that checks if an email exists in the database. So the database data is obtained through a webservice and with an input filter function the following JSON object is returned:
{"customers":{"customer":{"lastname":"test","firstname":"login","email":"nielsvanenckevort#hotmail.com"}}}
Now i would like to check if the email is filled in correctly. I'm using a foreach() statement to compare the values but i'm always getting a not found returned. Maybe someone here is able to find the mistake i've made. So the full code is shown down below.
$resultEmail = ($webService->get( $optUser ));
$emailResult = json_encode($resultEmail);
$emailArray = json_decode($resultEmail);
echo ($emailResult);
echo ($chopEmail);
foreach($emailArray->customers->customer as $item)
{
if($item->email == $email)
{
echo "found it!";
}
}
// The $optUser is the JSON object
Probably the quickest way would be strpos function, so you can use it this way
function hasEmail($string, $email)
{
return strpos($string, $email) !== false;
}
//example
echo hasEmail($resultEmail, $email) ? 'Has email' : 'Email not found';
The easiest way to do this would probably be to decode the string as an associative array instead of a json object, and then check if the key email exists using the array_key_exists function.
// passing true to json_decode will make it return an array
$emailArray = json_decode($resultEmail, true);
foreach($emailArray['customers'] as $customer) {
if(array_key_exists('email', $customer)) {
echo 'Found it!';
}
}
It seems your mistake come from the foreach loop. You should write it this way :
foreach($emailArray->customers as $customer) {
if($customer->email == $email) {
echo "found it!";
}
}
Please note that $emailArray is not an array but an object when you don't set the second parameter of the json_decode function :
$obj = json_decode($data);
$array = json_decode($data,true);
Related
I made this code
$message = 'This domain has strpos';
$links = array('domain.com', 'do.main');
$safe = strpos($message, $links);
return $message;
but got error errorHandler->error in my page, whats wrong with my code?
did I do some missing code?
what I want just detect if the message have string in $links then do rest of my code
thanks for droping out
Since PHP has no elegant solution and all I see is full blown functions here's a simple one that will work
$arr will hold an array of string you do NOT want
// If string has illegal characters return false
function str_allowed($str, $arr) {
foreach ($arr as $bad_string) {
if(strpos($str, $bad_string) !== false)
return false; // bad string detected, return false
}
return true; // if we got this far means everything's good return true
}
Please try this one will give expected output.
$message = 'This domain has strpos';
$links = array('domain.com', 'do.main');
$safe = array();
foreach($links as $key=>$result){
if(strpos($message, $result) != false){
$safe[$result] = "String is available";
} else{
$safe[$result] = "String is not available";
}
}
print_r($safe);
I am trying to use the following code to check if the current URL is within an array.
$reactfulPages = array(
'url-one',
'url-two',
'url-three',
);
if (strpos($url, $reactfulPages) == true) {
echo "URL is inside list";
}
I think the way I have set up the array is incorrect as the following code (checking for one URL) works fine..
if (strpos($url,'url-one') == true) { // Check if URL contains "landing-page"
}
Can anyone help me out?
The array is fine, the functions to check is not the right way. The strpos() function is for checking the string position(s).
The right way to check if something is in your array you can use the in_array() function.
<?php
$reactfulPages = array(
'url-one',
'url-two',
'url-three',
);
if(in_array($url, $reactfulPages)) {
echo "The URL is in the array!";
// Continue
}else{
echo "The URL doesn't exists in the array.";
}
?>
I hope this will work for you.
The function strpos() looks for a substring within a string, and returns the the position of the substring if it is found. That is why your last example works.
If you want to check whether something exists in an array, you should use the in_array() function, like so:
$reactfulPages = array(
'url-one',
'url-two',
'url-three',
);
if (in_array($url, $reactfulPages) == true) {
echo "URL is inside list";
}
However, since you're comparing URL's, I'm assuming you want to check whether the URL contains one of the strings from the array, not necessarily matching them as a whole.
In this case, you will need to write your own function, which could look like this:
function contains_any($string, $substrings) {
foreach ($substrings as $match) {
if (strpos($string, $match) >= 0) {
// A match has been found, return true
return true;
}
}
// No match has been found, return false
return false;
}
You can then apply this function to your example:
$reactfulPages = array(
'url-one',
'url-two',
'url-three',
);
if (contains_any($url, $reactfulPages)) {
echo "URL is inside list";
}
Hope this helps.
I have an interesting question today. Lets say I have an array of form fields:
array('field1', 'field2', 'field3');
I would basically want to generate an if statement which check if all of the provided fields are exists or not.
So something like this:
function ($array){
$stm = '';
foreach($array as $key){
$stm .= 'isset($_POST['.$key.']) && ';
}
if (rtrim($stm, ' && ')){
echo 'Fields are exists.';
}
}
The problem with the above function is that it takes the created statement as a String and not a variable, so it always exsits. Is there any way that I can generate something like this, which would work?
You're thinking about this the wrong way. If I understood correctly, you have an array of values, that are also POST keys, and you want to check if all of them are set. In this case I'd do something like:
function isset_multiple($array){
foreach($array as $post_key){
if(!isset($_POST[$post_key])) // if one of them is not set, return false
return false;
}
return true; // none of the foreach loops returned false, so all must be set
}
What you can do is check if array keys are set by using variable names, for example
$keyName = "field1";
if ( isset($_POST[$keyName]) === true ) { /* ... */ }
The example above can be implemented in a foreach loop.
Just execute the isset and count:
function ($array){
$count = 0;
foreach($array as $key){
if (isset($_POST[$key]) $count++;
else // you can already exit here...
}
if (count($array) === $count){
echo 'All fields exist.';
}
}
Try this..
function arrayHasKeys(array $array, array $keys)
{
return !((bool) array_diff_key($array, $keys));
}
var_dump(arrayHasKeys($_POST, array('field1', 'field2', 'field3')));
Its quite simple and reusable. Its not a good practice to use global vars inside a function.
I'm trying to check if the following is empty or not.
{"players":""}
I have a function that gets that from an api/site and.. well, heres the code.
function getPlayers($server) {
// Fetches content from url and json_decodes it
$playersList = getUrl('http://api.iamphoenix.me/list/?server_ip=' . $server);
// Attempting to check if it's empty.
if ($playersList != "") {
// convert list of comma-separated names into array
$players = explode(',', $playersList->players);
foreach ($players as $player) {
echo '<img title="'.$player.'" src="https://minotar.net/avatar/'.$player.'/32">';
}
} else {
return 'empty';
}
}
However, using !=, empty(), or isset(), I still get an empty string, example:
https://minotar.net/avatar//32
Where it should be..
https://minotar.net/avatar/Notch/32
When it's empty, I'd like it to just return 'empty'.
I'm not sure what I'm doing wrong. Any ideas?
In pure php you can check the url segments like
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', $_SERVER['REQUEST_URI_PATH']);
if($segments[2] == '') {
}
//or
if(empty($segments[2])) {
}
//or do your condition
if you are using codeigniter you might say
if(empty($this->uri->segment(2)))
But be sure you loaded the url helper
Hope I understand your question!
Since you were able to have some output, see my changes in the codes.
function getPlayers($server) {
// Fetches content from url and json_decodes it
$playersList = getUrl('http://api.iamphoenix.me/list/?server_ip=' . $server);
// Attempting to check if it's empty.
if ($playersList != "") {
// convert list of comma-separated names into array
$players = explode(',', $playersList->players);
// check conversion
if(is_array($players) && !empty($players){
foreach ($players as $player) {
echo '<img title="'.$player.'" src="https://minotar.net/avatar/'.$player.'/32">';
}
} else {
return 'empty';
}
} else {
return 'empty';
}
}
You should do this;
print_r($playersList);
just after you set it to see what it actually is. My guess is that you are not getting what you suspect from the getURL call.
Add one more equals sign to take type comparison into account as well
if ($playerList !== '')
try this
if (isset($playersList) && is_array($playersList) && !empty($playersList)) {
// convert list of comma-separated names into array
$players = explode(',', $playersList->players);
foreach ($players as $player) {
echo '<img title="'.$player.'" src="https://minotar.net/avatar/'.$player.'/32">';
}
} else {
return 'empty';
}
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);
}