Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Suppose that whe have some object, derived from these class instances
class A
{
...
private b //list of object of class B
}
class B
{
...
private c //list of object of class C
}
class C
{
...
private id
}
Now, somewhere in my code, I've got this situation
function findId(array $idList)
{
[...]
}
Where I have to find (for each element of $idList) if an element is contained into this object "cascade"
First solution
//object initialization
foreach($a->getB() as $b)
{
foreach($b->getC() as $c)
{
foreach($idList as $id)
{
if($id == $c->getId())
{
//do something an break the cycle
}
}
}
}
Second Solution
//object initialization
$idSet = array();
foreach($a->getB() as $b)
{
foreach($b->getC() as $c)
{
$idSet[] = $c->getId();
}
}
$idSet = array_unique($idSet);
foreach($idList as $id)
{
if(array_search($id,$idSet) !== false)
{
[...]
}
}
Which is better? There are some alternative methods for reach my goal?
IMPORTANT
There isn't better data representation. This because these objects are some database object (doctrine2)
You can actually combine the two approaches...
foreach($a->getB() as $b)
{
foreach($b->getC() as $c)
{
if (in_array($id, $idList)) {
...
And if you absolutely can't optimize in a way you won't have inner loop, set the values of $idList as keys, and values as true, and use isset() instead of in_array(), since it's the fastest
I would say that both are bad, they will in worst case give O(n^3), cause of the three for each loops. Is there maybe a better represenation of the data, in order to avoid all these loops?
If the answer is no, i would go with the first approach in order to avoid creating a new set.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am looking for smart solution, maybe you could help me out. Currently I am doing an own Authentication (Separate Class) system for my Webshop project. My problem is, that I need conditional statement inside foreach loop, to return the code (see below). Any suggestions?
My code currently look like this
public function regiAuth($email, $password, $firstname, $lastname)
{
$authContainer = [$email, $password, $firstname, $lastname];
foreach ($authContainer as $a) {
return !empty($_POST[$a]);
}
}
And I want to result this (With &&)
return !empty($_POST[$email]) && !empty($_POST[$password]) &&
!empty($_POST[$firstname]) && !empty($_POST[$lastname])
I believe you could do simply by do
foreach ($authContainer as $a) {
if (empty($_POST[$a])
return false;
}
return true;
instead of checking if all of them are full, you look if there is at least one empty.
it is a good practice to stop iteration if you find one element that is not as expected, imagine if you had an array of hundreads of assertions to do.
making an full if statement would look like this, here it checks if the $_POST are not empty. && means that both have to true or false
foreach ($authContainer as $a) {
if((!$_POST[$email]) && (!$_POST[$password])){
return false;
}
}
return true;
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Does PHP have keyword or feature that shortens code and repetition like jquery $(this)?
For example
// How to avoid typing same variable twice
echo isset($_POST['foo']) ? $_POST['foo'] : '';
In Jquery
<script>
// Avoid typing $("#button-element") again
$("#button-element").click(function() {
$(this).css("border-color", "#000");
});
</script>
No. And that code wouldn't work in JS either.
In JS, this is -- roughly speaking -- the object that the current function was called as a method on. It is not "the last thing I mentioned". The JS equivalent of your second code:
_POST['foo'] ? this : ''
would return an object if _POST['foo'] were set. It would not return the value of _POST['foo'].
There is no variable like the one you're looking for in any language I've ever used.
of course it does! you need to construct this across a class.
It works about the same as in javascript ES6 class.
$number = 4;
$This = new demoThis($number);
$This->multiplyThis(4);
class demoThis {
private $number;
private $factor;
public $result;
public function __construct($number) {
$this->number = $number;
}
function multiplyThis($factor) {
$this->factor = $factor;
$this->result = $this->number * $this->factor;
return $this->result;
}
}
echo isset($_POST['foo']) ? $This->result : '';
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I find myself doing the following quite a bit:
if (isset($objs[$key]){
$objs[$key] += val;
} else {
$objs[$key] = $val;
}
Is there a better way to do that?
Another way could be:
$objs[$key] = isset($objs[$key]) ? $objs[$key] + $val : $val
Is there a better way?
The easiest way to simplify could be a function taking the array by reference and deduplicate the code.
If you are using php 7 you can also make use the new ?? operator (assuming all values are integers):
$arr[$key] = ($arr[$key] ?? 0) + $value;
However, if you know the shape of the array you should base your actions on that. Create the array using array_fill_keys or similiar in that case.
If you are always adding numbers... you could do something like this to keep a single line of code for each entry which may or may not be preferable for you to your existing solution.
$objs = array();
addvalue($objs, "dog", 2);
addvalue($objs, "dog", 5);
// $objs['dog'] will = 7
function addvalue(& $var, $key, $value){
if (isset($var[$key])){
$var[$key] += $value;
} else {
$var[$key] = $value;
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I was making a class in PHP for validation of a contact form, when I hit a problem. I eventually tracked it down to an array within the class, and wrote a test script to try to solve the problem:
<?php
class Object {
public $testArray = array(5);
function __construct() {
$testArray[] = 7;
}
function addNumber() {
$testArray[] = mt_rand(10,20);
}
function returnArray() {
return var_dump($testArray);
}
}
$object = new Object;
$object->addNumber();
echo($object->returnArray());
var_dump($object->testArray);
This outputs NULL array(1) { [0]=> int(5) }.
I am confused as to why this does not work. Eventually I would like the array to be private, but I can't find a way similar to get and set in C#. Any ideas?
Give this a go:
class Object {
public $testArray = array(5);
function __construct() {
$this->testArray[] = 7;
}
function addNumber() {
$this->testArray[] = mt_rand(10,20);
}
function returnArray() {
return var_dump($this->testArray);
}
}
You have to reference the class variable using $this - otherwise it'll try to set a variable local to the function you're in.
You can use PHP's magic __set() and __get() methods for similar functions to C# that you mentioned: PHP Overloading.
$testArray[] = mt_rand(10,20);
Should be:
$this->testArray[] = mt_rand(10,20);
$testArray is just another local variable (local to the function, no the class). If it has no value it is null. This is consistent with the output you're seeing. $object->testArray is never modified.
You have to access class variables using $this. So $testArray should be $this- >testArray.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
What I am doing wrong with the following code? I want to compare if the element $my_id is present within the array $arr. If it is present return TRUE else return FALSE.
for($i=0;$i<$cnt;$i++)
{
if($arr[$i] == $my_id)
{
return TRUE;
}
else
{
return FALSE;
}
}
You could replace that with...
return in_array($my_id, $arr);
...assuming you don't really want to return FALSE if the first element does not match.
If that is actually what you wanted, you could use...
return $arr[0] == $my_id;
If you want to leave your code mostly intact, just move the return FALSE to outside of the loop body.
The issue you are having is that you aren't looping entirely through the array. You are returning true/false after the first item in the array, irrespective of subsequent array entries after [0]
Well, I believe you should remove the else statement, unless you always just have one element in the array. I mean -- from the example you're showing, you're exiting the loop with this. I doubt this is what you want.
If you just need to know, if a value is within a given array
in_array($value, $array);
Maybe you want get the index of (the first occurence of) the value too
$index = array_search($value, $array);
if ($index === false) {
// Not in array
} else {
echo $array[$index];
}
The error in Your code is to return false on $arr[$i] != $my_id. The algorithm should look something like this:
for($i=0;$i<$cnt;$i++)
{
if($arr[$i] == $my_id)
{
return TRUE;
}
}
return FALSE;
P.S. This isn't the best solution for this problem in PHP language. You should use one from alex.