The answer to this problem is SUPPOSED to be 15, but with this code I'm getting 10. My professor told me to check the operator in the loop, but I don't know what that means. ANY help with be appreciated!!
function addThemUp($parameter1) {
$total=i;
for ($i=0;$i<$parameter1;$i++) {
$total=$total+$i;
};
return $total;
};
Try this:
function addThemUp($parameter1) {
$total=0;
for ($i=0;$i<$parameter1;$i++) {
$total++;
}
return $total;
}
This should work fine.
Btw, when you wrote
$total=i;
i is not defined.
Also, don't add a semicolon after functions/for loops ;)
Good luck!
Your initial $total = i is a problem because i has no defined value. I think you want $total = 0
I also think your loop should range from 1 to = $paramater1
function addThemUp($parameter1) {
$total=0;
for ($i=1; $i <= $parameter1; $i++) {
$total += i;
};
return $total;
}
Related
So the loop isn't printing and I don't understand why? I'm only a beginner so I'm really confused on why it won't work. If you guys could explain the reason behind it too that would be great.
<html>
<body>
<?php
$numbers = array(4,6,2,22,11);
sort($numbers);
function printarray($numbers, $x) {
$countarray = count($numbers);
for($x = 0; $x < $countarray; $x++) {
echo $numbers[$x];
echo "<br>";
}
}
printarray();
?>
</body>
</html>
You need to add your variable to your function:
printarray($numbers);
You can also remove the $x from the function as it is being created and destroyed in the function itself.
Since you are a beginner, you might be interested in learning about foreach. You can use it to greatly simplify your function like so:
<?php
$numbers = array(4,6,2,22,11);
sort($numbers);
function printArray($nums) {
foreach($nums as $num) {
echo $num;
echo "<br>";
}
}
printArray($numbers);
Experiment via: https://3v4l.org/1BtkK
Once you get used to using foreach, take a look at array_map, array_filter, and array_reduce as ways to simplify your code even more.
<?php
$numbers = array(4,6,2,22,11);
$sort($numbers);
function printArray($nums) {
array_reduce($nums, function ($carry, $item) {
echo $carry .= $item . "<br>";
});
}
printArray($numbers);
Experiment via: https://3v4l.org/4JJFL
And since you are a beginner, check out PHP The Right Way and practice. Once you have gained experience, check out PHP The Right Way again and practice some more. And again. And again.
I am looking for a PHP solution to use a loop to go through to capture all the data
Here is an example of a lookup without using a loop
if (array_key_exists('utf8String', $cert['tbsCertificate']['subject']['rdnSequence'][0][0]['value'])) {
// do somthing
} else if (array_key_exists('printableString', $cert['tbsCertificate']['subject']['rdnSequence'][0][0]['value'])) {
// do somthing
} else if (array_key_exists('bmpString', $cert['tbsCertificate']['subject']['rdnSequence'][0][0]['value'])) {
// do somthing
} else if (array_key_exists('telextexString', $cert['tbsCertificate']['subject']['rdnSequence'][0][0]['value'])) {
// do somthing
}
I need the loop to go through the entire array. For ONLY the first [ ] the loop should increase the integer [0] to 1, [2] and so forth until its gone through the whole lot. In case you are wondering, the second [ ] is always [0] so that needs to remain as is.
Right now I am copying/pasting the above about 20 times and manually updating the number in the first box but I am hoping there is a more elegant way to achieve that.
-- MORE CONTEXT --
-- WORKING CODE -- offered by #Ghost
$count = count($cert['tbsCertificate']['subject']['rdnSequence']);
$exists = array('utf8String', 'printableString', 'teletexString');
$oid = array('id-at-stateOrProvinceName', 'id-at-countryName', 'id-at-localityName', 'id-at-commonName', 'id-at-organizationalUnitName');
for($i = 0; $i < $count; $i++) {
foreach($exists as $field) {
if(array_key_exists($field, $cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['value'])) {
$value = $cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['value'][$field];
echo $value, ' [',$field, ']',"\n";
}
}
}
You can just add another loop inside applying each field into array_key_exists, this applies to #Markus' idea anyway:
$count = count($cert['tbsCertificate']['subject']['rdnSequence']);
$exists = array('utf8String', 'printableString', 'teletexString');
$oid = array('id-at-stateOrProvinceName', 'id-at-countryName', 'id-at-localityName', 'id-at-commonName', 'id-at-organizationalUnitName');
for($i = 0; $i < $count; $i++) {
foreach($exists as $field) {
if(array_key_exists($field, $cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['value'])) {
$value = $cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['value'][$field];
$k = array_keys($cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['type']);
$oid = reset($k);
break;
}
}
}
[ EDIT: Please see the comments below. ] How about for simples...
$strings = ['utf8String', 'printableString' ... ];
foreach ($strings as $string) { // do your checks etc. }
I suppose you know how to increment a counter in a loop. $i++ and stuff, use [$i] wherever you need to increment the reference value in your $cert array. On match, break or continue in place of else if, depending on what exactly you need to accomplish here. Your objectives aren't too clear in the question, could share a bit more insight...
Here is my code :
<?php
$a=array(10,8,6,5);
$b=count($a);
for($i=0;$i<($b-1);$i++)
{
for($j=1;$j<($b);$j++)
{
if($a[$j]<$a[$i])
{
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
I just want to know what's wrong in the above code ? because if i take 3 array values it works fine but for 4 its not working....can someone do the modification for the same code,and also please briefly explain why is it not working any issues with looping?I am not looking for different code.
You have mistakenly modified the bubble sort algorithm. Use standard one.
<?php
$a=array(10,8,6,5);
$b=count($a);
for($i=0;$i<($b);$i++) //Changes over here
{
for($j=0;$j<($b);$j++) //Changes over here
{
if($a[$j]>$a[$i]) //Changes over here
{
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
Why are you manually sorting when you have sort?
$a = array(10,8,6,5);
sort($a);
var_dump($a);
Similarly, why are you using temporary variables when you have list?
list($a[$i],$a[$j]) = array($a[$j],$a[$i]);
try below code may be that will help.
<?php
function pr($array = array())
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$a = array(10,8,6,5);
$b = count($a);
for($i=0;$i <= ($b-1);$i++)
{
for($j=0; $j < ($b);$j++)
{
if($a[$j] < $a[$i])
{
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
pr($temp);
pr($a);
?>
<?php
$a=array(8,6,5);
$b=count($a);
for($i=0;$i<($b);$i++)
{
for($j=0;$j<($b);$j++)
{
if($a[$j]<$a[$i])
{
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
The inner loop doesn't need to be executed n times (where n=number of elements to be sorted). Every time the outer loop executes, one more element at the end (for ascending order) is in the correct position. So, inner loop should not check those elements.
<?php
$a=array(10,8,6,5);
$b=count($a);
for($i=0;$i<($b);$i++){
for($j=0;$j<($b-$i);$j++){ // this change will save time
if($a[$j]>$a[$i]){
$temp = $a[$j];
$a[$j]=$a[$i];
$a[$i]=$temp;
}
}
}
?>
i have a very simple question. How can i make this code
$i = 0;
foreach($Array as $Value)
{
echo $i;
$i++
}
but written like this?
foreach($Array as $Value)
{
$i = 0;
echo $i;
$i++
}
should i use a STATIC variable? or what? I don't have a clear view on this.
Thank you!
You shouldn't really do that. static variables are used to persist a variable's value between invocations of the function they're embedded in. They're not useful for a simple loop. Your second code will simply reset the counter to zero on every iteration.
e.g. this is a correct usage:
function count() {
static $x = 0; // executed the first time count() is called, then never again"
echo ++$x;
}
count(); // 1
count(); // 2
count(); // 3
You can certainly have
foreach($array as $val) {
static $x = 0;
echo ++$x;
}
but you don't gain anything, since that particular piece of code never goes out of scope for the duration of the loop, so $x's value would never get "lost".
you may want use
foreach($Array as $i => $Value)
{
echo $i;
}
or
foreach(array_values($Array) as $i=>$Value)
{
echo $i;
}
While first your example is correct, too
I am studying OOP and this is my first study project.
I created a Math class and also created an add method. But when I am trying to create a subtract method I don't know where I am getting a problem.
Please kindly help and give me information where I can get more detailed information on OOP.
<?php
class Math
{
/**
*
* #return int
*/
function add()
{
$args = func_num_args();
$sum = 0;
$i = 0;
for ( $i; $i < $args; $i++ )
{
is_int(func_get_arg($i)) ? $sum += func_get_arg($i) : die('use only integers, please');
}
return $sum;
}
function subtract()
{
$args = func_num_args();
$sub = 0;
$i = 0;
while($i < $args)
{
$sub = func_get_arg($i);
if (is_int(func_get_arg($i)))
{
is_int($sub - func_get_arg($i));
}
}
$i++;
return $sub;
}
}
I am calling this class in my index.php like this:
<?php
include("Math.php");
$c = new Math();
$result = $c->subtract(100,10,20,45);
echo $result;
?>
There are a few small problems here:
Your loop won't ever terminate because the incrementing of $i is outside of your while loop.
The setting of $sub the first time should happen before the while loop. I assume your subtraction function is meant to subtract the latter arguments from the first argument. Right now, $sub is reset every pass through the loop.
$sub's value is never updated by the subtraction operation in your loop. You need to assign a new value to $sub based on the subtraction. You can use the -= shorthand for this just like you used the += shorthand in your add() method.
A working solution would look like this:
$sub = func_get_arg( $i ); // At this point $i == 0
while ( $i < $args ) { // Loop while $i is less than the number of args
$i++; // Increment $i
$operand = func_get_arg( $i ); // Name the argument for clarity
if ( is_int( $operand )) { // Make sure the $operand is an integer
$sub -= $operand; // Update $sub by subtracting $operand from it
} else {
// Do some error handling here...
}
}
I would recommend for you to watch this video The Clean Code Talks -- Inheritance, Polymorphism, & Testing.
This might help you to understand OOP better, and one of examples in the talk is very similar to one you are trying to make.
The functional line is_int($sub - func_get_arg($i)); is incorrect. I think you intend to use this as a ternary operator and add additional logic. Here is my rewrite:
public function subtract() {
$args = func_get_args();
$sub = array_shift($args);
foreach ($args as $arg) {
is_int($sub - $arg) and $sub -= $arg
or die('use only integers please');
}
return $sub;
}
You could also do that using array_reduce() and bcsub() (or other subtraction function):
$sub = array_reduce(array_slice(func_get_args(), 1), 'bcsub', func_get_arg(0));