I'm getting a syntax error and I can't figure out why. "Parse error: syntax error, unexpected '{' on line 6"
function ExtractCustomField($fieldName, $customFields) {
// $customFields might be an object, NULL, or an array.
$parsed = array();
if (is_array($customFields) == false && $customFields != null) {
$parsed = array($customFields);
} else (is_array($customFields)) {
$parsed = $customFields;
}
// loop through the fields and find the one we are looking for
$returnField = null;
foreach($field as $customFields) {
if ($field->Name == $fieldName) {
$returnField = $field;
break;
}
}
return $returnField
}
You forget to put semicolon after $returnField, also use elseif instead of else (else don't need any arguments). Use the code below
function ExtractCustomField($fieldName, $customFields) {
// $customFields might be an object, NULL, or an array.
$parsed = array();
if (is_array($customFields) == false && $customFields != null) {
$parsed = array($customFields);
} elseif (is_array($customFields)) {
$parsed = $customFields;
}
// loop through the fields and find the one we are looking for
$returnField = null;
foreach($field as $customFields) {
if ($field->Name == $fieldName) {
$returnField = $field;
break;
}
}
return $returnField;
}
Hope this helps you
else doesn't take any expression after it. Either remove the expression or use elseif instead.
You have missed semicolon in return
return $returnField;
}
Also Else condition else (is_array($customFields)) format is wrong....else dont take any condition after it...You can use Elseif instead
else (is_array($customFields)) {
Is invalid. Use either else if or remove the condition
function ExtractCustomField($fieldName, $customFields) {
// $customFields might be an object, NULL, or an array.
$parsed = array();
if (is_array($customFields) == true && $customFields != null) {
$parsed = array($customFields);
} else {
$parsed = $customFields;
}
// loop through the fields and find the one we are looking for
$returnField = null;
foreach($field as $customFields) {
if ($field->Name == $fieldName) {
$returnField = $field;
break;
}
}
return $returnField;
}
It should else if(is_array($customFields)) or elseif(is_array($customFields))
I have modified your function, i see there is supposed to be and elseif instead of else and in the foreach loop, the syntax in your code was wrong. I have also assumed that you will be using a single level associative array.
<?php
function ExtractCustomField($fieldName, $customFields) {
// $customFields might be an object, NULL, or an array.
$parsed = array();
if (is_array($customFields) == false && $customFields != null) {
$parsed = array($customFields);
} elseif (is_array($customFields)) {
$parsed = $customFields;
}
// loop through the fields and find the one we are looking for
$returnField = null;
foreach($customFields as $field) {
if ($field == $fieldName) {
$returnField = $field;
break;
}
}
return $returnField;
}
echo ExtractCustomField('name', array('name','emial','mobile','password'));
?>
Related
I update my code from PHP 5 to PHP 7 and i got problem with foreach loop. I loocked wor answers here, but none is working. Or i dont understand where i have problem
function getStructure($pid = 0, $expand = array(), $alevel = 0)
{
$struct = array();
if ( $alevel > $this->levelCount) $this->levelCount = (int)$alevel;
$str = $this->dbStructure->getStructure($pid);
foreach ($str as &$row)
{
if ($row["type"] == STRUCT_PAGE)
{
$row["editLink"] = "editPage";
$row["target"] = "_self";
}
elseif ($row["type"] == STRUCT_MODULE)
{
$row["editLink"] = "editModule";
$row["target"] = "_self";
}
elseif ($row["type"] == STRUCT_LINK)
{
$row["editLink"] = "editLink";
$row["target"] = "_blank";
}
elseif ($row["type"] == STRUCT_CATALOG)
{
$row["editLink"] = "editCatalog";
$row["target"] = "_self";
}
$row["childrens"] = $this->getStructure((int)$row["id"], $expand, $alevel+1);
if ($row["type"] == STRUCT_CATALOG and isset($row["childrens"][0]["shortcut"]))
{
$row["shortcut"] = $row["childrens"][0]["shortcut"];
$row["target"] = $row["childrens"][0]["type"] == STRUCT_LINK ? "_blank" : "_self";
}
$struct[] = $row;
}
unset($row);
return $struct;
}
All the time $struct is NULL and I need to be multidimensional array
This code by itself is good. Has no problems, only ampersand is not needet. The problem was in different place. Sorry for spam
<!-- language: php -->
<?php
// test variables
$l1 = "http://youtube.com/channel/";
$l2 = "http://youtube.com/channel/";
$l3 = "http://youtube.com/channel/";
$l4 = "http://youtube.com/channel/";
$fl = "http://youtube.com/channel/";
//set error false as default
$error = "false";
//check if variables are ready for use, if they are, add them to `$l` array
//I do each check as a seperate line, as it looks cleaner than 1 long if statement.
$l = [];
if(!empty($l1)) $l[] = $l1;
if(!empty($l2)) $l[] = $l2;
if(!empty($l3)) $l[] = $l3;
if(!empty($l4)) $l[] = $l4;
if(!empty($fl)) $l[] = $fl;
foreach($l as $key => $value) {
//1 line ternary is cleaner than if/else statetmnt
$errorKey = $key < 9? "0{$key}" : $key;
//each row by default has no error
$hasError = 0;
//check if this a valid url
if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $value)) {
$error = "true";
$hasError = 1;
}
if($hasError) {
//store error in array, to loop through later
$errors[] = $errorKey;
}
}
$search = '?sub_confirmation=1';
$searchUrl = "youtube.com/channel";
if (strpos($l, $searchUrl) !== false && strpos($l, $search) === false) {
$l = $value."".$search;
}
if($error == "false") {
echo $l1;
echo $l2;
echo $l3;
echo $l4;
echo $fl;
}
// deliver the error message
//Check if $error has been set to true at any point
if($error == "true") {
//loop through error array, echo error message if $errorNumber matches.
//at this point we KNOW there was an error at some point, no need to use a switch really
foreach($errors as $errorNumber) {
echo "Something went wrong here $errorNumber :o";
}
}
?>
Hello, my problem is at the end of the code where the strpos function is, so basically I want to check every url, once if it contains a certain url, and then add something to the end if it is so. But I don't want to repeat an if statement 4 times($fl variable doesn't has to be checked), I am quite new in all that so I hope somebody can help me, I tought about a switch statement but I guess there is a better way. And if I put it in the foreach aboth, it doesn't applies on the certain variables, only on the value variable.
You can assign $value by reference using this foreach header (notice the & in front of $value):
foreach($l as $key => &$value) {
By doing this every change you do to $value will also be done to the corresponding value in the $l array.
Then at the end of the foreach loop you put this code:
if (strpos($value, $searchUrl) !== false && strpos($value, $search) === false) {
$value .= $search;
}
So your final foreach loop should look like this:
foreach($l as $key => &$value) {
//1 line ternary is cleaner than if/else statetmnt
$errorKey = $key < 9? "0{$key}" : $key;
//each row by default has no error
$hasError = 0;
//check if this a valid url
if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $value)) {
$error = "true";
$hasError = 1;
}
if($hasError) {
//store error in array, to loop through later
$errors[] = $errorKey;
}
$search = '?sub_confirmation=1';
$searchUrl = "youtube.com/channel";
if (strpos($value, $searchUrl) !== false && strpos($value, $search) === false) {
$value .= $search;
}
}
You can read more about using references in foreach loops here: PHP: foreach
Edit:
To apply the changes not only to the elements of the $l array, but also to the original variables $l1, $l2 and so on, you should assign the elements to your array as references too:
$l = [];
if(!empty($l1)) $l[] = &$l1;
if(!empty($l2)) $l[] = &$l2;
if(!empty($l3)) $l[] = &$l3;
if(!empty($l4)) $l[] = &$l4;
if(!empty($fl)) $l[] = &$fl;
Personally, I think this is a good candidate for moving to a class. To be honest I'm not 100% sure what you are doing but will try to convert your code to a class.
class L {
public $raw = null;
public $modified = null;
public $error = false;
// create the class
public function __construct($data=null) {
$this->raw = $data;
// Check the raw passed in data
if ($data) {
$this->isUrl();
}
// If there was no error, check the data
if (! $this->error) {
$this->search();
}
}
// Do something ?
public function debug() {
echo '<pre>';
var_dump($this);
echo '</pre>';
}
public function getData() {
return ($this->modified) ? : $this->raw;
}
private function isUrl() {
$this->error = (! preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $this->raw));
}
// Should a failed search also be an error?
private function search() {
if ($this->raw) {
if ( (strpos($this->raw, "youtube.com/channel") !== false) &&
(strpos($this->raw, "?sub_confirmation=1") === false) ) {
$this->modified = $this->raw ."?sub_confirmation=1";
}
}
}
}
// Test data
$testList[] = "test fail";
$testList[] = "https://youtube.com/searchFail";
$testList[] = "https://youtube.com/channel/success";
$testList[] = "https://youtube.com/channel/confirmed?sub_confirmation=1";
// Testing code
foreach($testList as $key=>$val) {
$l[] = new L($val);
}
foreach($l as $key=>$val) {
// Check for an error
if ($val->error) {
$val->debug();
} else {
echo '<pre>'.$val->getData().'</pre>';
}
}
And the output would be:
object(L)#1 (3) {
["raw"]=>
string(9) "test fail"
["modified"]=>
NULL
["error"]=>
bool(true)
}
https://youtube.com/searchFail
https://youtube.com/channel/success?sub_confirmation=1
https://youtube.com/channel/confirmed?sub_confirmation=1
So I started using MVC. I don't use a framework. It's just self-practice.
So this is my register part:
protected function _instance()
{
if ($_POST != null)
{
/**
* Validating if forms are not empty
**/
if (self::validateForms())
{
echo 1;
}
else
{
new Error("One of the forums was empty..");
}
}
}
private static function validateForms()
{
$inputs = array (
'username', 'password', 'repassword',
'email', 'password_f', 'repassword_f',
'display'
);
$i = 0;
foreach ($inputs as $key)
{
if (isset($_POST[$key]) && !empty($_POST[$key]))
{
$i++;
if ((int) $i == count($inputs))
{
return true;
}
else
{
return false;
}
}
}
}
Now it only must check if inputs were set, if not, throw error.
But it seems like it doesn't work as it always runs that error.
$i must grow everytime a input was full, but I don't think it does.
When I do echo $i, it only echoing "1".
Why is it only looping through it once?
The problem is you are returning within your loop after the first test.
foreach ($inputs as $key)
{
if (isset($_POST[$key]) && !empty($_POST[$key]))
{
$i++;
if ((int) $i == count($inputs))
{
return true;
}
else
{
return false;
}
}
}
should be
foreach ($inputs as $key)
{
if (isset($_POST[$key]) && !empty($_POST[$key]))
{
$i++;
}
}
if ((int) $i == count($inputs))
{
return true;
}
else
{
return false;
}
or more concisely
foreach ($inputs as $key)
{
if (!isset($_POST[$key]) || empty($_POST[$key]))
{
return false;
}
}
return true;
You need to take the checking of $i out of the loop so that it checks how many were actually set once all the inputs have been cycled through. Otherwise, it is checking on the first time, seeing that it is not equal and returning false.
foreach ($inputs as $key)
{
if (isset($_POST[$key]) && !empty($_POST[$key]))
{
$i++;
}
}
if ((int) $i == count($inputs))
{
return true;
}
else
{
return false;
}
i have this code. Basically identifies if any position of array is empty or have an input equal a zero.
$fields = array("first", "second", "third");
function check($fields, $form) {
foreach($fields as $field) {
if(empty($form[$field]) || $form[$field] === 0) {
echo 'empty';
return false;
break;
}
}
}
My doubt now, is , how i can do an echo for example to show the second position is empty?
with an if? if ($form[$field][second]) ? i don't know if this is correct, or exists a better option
thanks
if $field is what you want to echo then just prepend it to 'is empty':
$fields = array("first", "second", "third");
function check($fields, $form)
{
foreach($fields as $field)
{
if(empty($form[$field]))
{
echo $field.' is empty';
return false;
}
}
}
if you need the index value:
$fields = array("first", "second", "third");
function check($fields, $form)
{
foreach($fields as $k=>$field)
{
if(empty($form[$field]))
{
echo $k.' is empty';
return false;
}
}
}
eventually if the aim is retrieve the empty position (if check returns -1 then there are no empty positions):
$fields = array("first", "second", "third");
function check($fields, $form)
{
foreach($fields as $k=>$field)
{
if(empty($form[$field]))
return $k;
}
return -1;
}
Can't you do something like the following:
if (empty($form[$field+1])) {
echo 'Empty';
}
Use a recursive function like this:
function isEmpty($array){
if(is_array($array)){
foreach($array as $key=>$value){
if(isEmpty($value) !== false) return $key;
}
return false;
}else{
if($array === 0 || empty($array)){
return true;
}
}
}
This will traverse the array as deep as it goes, and return the index where it found an empty position, or false if it did not find an empty position.
Maybe I'm in totally wrongness, but why not :
if(empty($form[2]) || $form[2] === 0) {
echo 'second element is empty';
}
If your question is 'How can I know at what index am I while doing a foreach', then the answer is that :
$fields = array("first", "second", "third");
function check($fields, $form) {
foreach($fields as $i => $field) {
if ( (empty($form[$field]) || $form[$field] === 0) && ($i == 2)) {
echo '2n element is empty';
return false; // no need to break; as you have returned something.
}
}
}
I am currently optimizing a PHP application and found one function being called around 10-20k times, so I'd thought I'd start optimization there:
function keysToLower($obj)
{
if(!is_object($obj) && !is_array($obj)) return $obj;
foreach($obj as $key=>$element)
{
$element=keysToLower($element);
if(is_object($obj))
{
$obj->{strtolower($key)}=$element;
if(!ctype_lower($key)) unset($obj->{$key});
}
else if(is_array($obj) && ctype_upper($key))
{
$obj[strtolower($key)]=$element;
unset($obj[$key]);
}
}
return $obj;
}
Most of the time is spent in recursive calls (which are quite slow in PHP), but I don't see any way to convert it to a loop.
What would you do?
This version doesn't account for associative arrays since my data doesn't have any, but is nearly 10 times faster than the original version. Most of the work was done by Gumbo, the major speedup comes from using references and creating a new object instead of unsetting the old keys.
function &keysToLower(&$obj)
{
if(is_object($obj))
{
$newobj = (object) array();
foreach ($obj as $key => &$val)
$newobj->{strtolower($key)} = keysToLower($val);
$obj=$newobj;
}
else if(is_array($obj))
foreach($obj as &$value)
keysToLower($value);
return $obj;
}
Foreach is using an internal copy that is then traversed. Try it without:
function keysToLower($obj)
{
$type = (int) is_object($obj) - (int) is_array($obj);
if ($type === 0) return $obj;
reset($obj);
while (($key = key($obj)) !== null)
{
$element = keysToLower(current($obj));
switch ($type)
{
case 1:
if (!is_int($key) && $key !== ($keyLowercase = strtolower($key)))
{
unset($obj->{$key});
$key = $keyLowercase;
}
$obj->{$key} = $element;
break;
case -1:
if (!is_int($key) && $key !== ($keyLowercase = strtolower($key)))
{
unset($obj[$key]);
$key = $keyLowercase;
}
$obj[$key] = $element;
break;
}
next($obj);
}
return $obj;
}
Or use references to avoid that a copy is used:
function &keysToLower(&$obj)
{
$type = (int) is_object($obj) - (int) is_array($obj);
if ($type === 0) return $obj;
foreach ($obj as $key => &$val)
{
$element = keysToLower($val);
switch ($type)
{
case 1:
if (!is_int($key) && $key !== ($keyLowercase = strtolower($key)))
{
unset($obj->{$key});
$key = $keyLowercase;
}
$obj->{$key} = $element;
break;
case -1:
if (!is_int($key) && $key !== ($keyLowercase = strtolower($key)))
{
unset($obj[$key]);
$key = $keyLowercase;
}
$obj[$key] = $element;
break;
}
}
return $obj;
}
You might also want to lookup array_change_key_case()
I assume you don't care about casting to array...
function keys_to_lower($o) {
if (is_object($o)) {
$o = (array)$o;
}
if (is_array($o)) {
return array_map('keys_to_lower', array_change_key_case($o));
}
else {
return $o;
}
}
here a example using lambda:
$multiArrayChangeKeyCase = function (&$array) use (&$multiArrayChangeKeyCase) {
$array = array_change_key_case($array);
foreach ($array as $key => $row)
if (is_array($row))
$multiArrayChangeKeyCase($array[$key]);
};
array_combine(array_map("strtolower", array_keys($a)), array_values($a))
A some what late response to a old thread but, there's a native function that does this, you could wrap it up something along these lines.
function setKeyCasing($thing, $case = CASE_LOWER) {
return array_change_key_case((array) $thing, $case);
}