₦airaland Forum

Welcome, Guest: RegisterLoginWith GoogleTrendingRecentNew

Stats: 3,325,626 members, 8,422,903 topics. Date: Tuesday, 09 June 2026 at 02:19 AM

Toggle theme

PHP Simple Puzzle - Webmasters (2) - Nairaland

Nairaland ForumScience/TechnologyWebmastersPHP Simple Puzzle (4096 Views)

1 2 3 Reply (Go Down)

Re: PHP Simple Puzzle by Nobody:
Web Contractor: NEW PUZZLE
Given the array below,write a PHP conditional statement that returns 2,4,8,10

<?php

$even_numbers = array(2,4,6,8,10,12);

?>;


Difficulty Level: Intermediate
Hint:Use Loops

Edit: Remove the last Comma from your result
Already our puzzle is half way answered,I would have loved to finish it off but will be delighted to see Geraldcole or Judinho59 put finishing touches to their concepts.However,I will be answering the puzzle from a different approach while waiting for the previously proposed solutions.
This will work in simple cases.

<?php

$even_numbers = array(2,4,6,8,10,12);

//using each value in even numbers array

foreach($even_numbers as $new)
{
if (($new == 6) || ($new == 12))
{ continue;
}
echo $new;
if($new ==10)
{ break;
}
echo ",";
}

?>

Result
2,4,8,10

Officially the Puzzle is still unanswered.
Re: PHP Simple Puzzle by Nobody:
@Web Contractor: I Didnt test that code, was busy by then. iGuess the rtrim() didnt work with the Loop.


<?php
$even_numbers = array('2','4','6','8','10','12');
$arr = array();
$out = array('6','12');
foreach($even_numbers as $value) {
if(!in_array($value, $out)){
$arr[] = $value;
}
}
$value = implode(",", $arr);
echo $value;

?>


Result:
2,4.8,10
Re: PHP Simple Puzzle by Nobody: 3:03pm On Apr 14, 2013
<?php
$even_numbers = array('2','4','6','8','10','12');

$remove_12_6_from_array = array_diff($even_numbers , array('6', '12'));

echo $even_numbers = implode ( "," , $remove_12_6_from_array );

?>

YOU DO NOT NEED ANY LOOP.
Re: PHP Simple Puzzle by Nobody: 3:31pm On Apr 14, 2013
ActiveMan: <?php
$even_numbers = array('2','4','6','8','10','12');

$remove_12_6_from_array = array_diff($even_numbers , array('6', '12'));

echo $even_numbers = implode ( "," , $remove_12_6_from_array );

?>

YOU DO NOT NEED ANY LOOP.
Ofcourse, but see it as a Challenge where a Loop must be used.
Re: PHP Simple Puzzle by Gerardcole(m): 3:39pm On Apr 14, 2013
I usually type on my android device so sorry for the errors. I didn't close a line with ;. Also I didn't close the if containing the in_array(), then I interchanged the position of the values in in_array. So editing the former post, here is the solution.


Okay. Since according to our puzzle provider, Judinho59 didn't get the required output, I ll provide my own solution. The puzzle is kinda tricky.

Given array('2', '4', '6', '8', '10', '12')
To return 2,4,8,10 (Removing 6 and 12 and the last comma that's supposed to appear after 10)

I'm also gonna attack in two methods.

1. Using PHP in_array()

<?php
/* First we set the values we do not want in an array */
$unwanted = array('6', '12');

/*Then we set a variable which will help in placing comma's */

$counter = 0;

/*Then to the code */
$ev = array('2', '4', '6', '8', '10', '12');

foreach($ev as $a)
{
if(!in_array($a, $unwanted))
/*Checks if $a is not in our unwanted list before proceeding*/
{
if($counter > 0)
/* Since we don't want it after our last value but after every other, we run this before the value. > 0 here explains that we don't want it before the first as our counter is still 0 before this line */
{
echo ', ';
}
echo $a;
$counter++;
/*In PHP ++ is same as +1 so whenever it gets to the line above, the counter is increased buly 1*/
}

}
?>

2. Using the modulus operator '%'

The modulus %, in PHP returns the remainder in a division operation. E.g 7 % 5 returns 2 (i.e 1 remaining 2), 10 % 5 returns 0 (i.e 2 remaining 0).

I wouldn't be explaining the lines I already explained in example 1 above.

<?php
$div = 6;
/* Since all the unwanted numbers are divisible by 6. */

$counter = 0; //As explained in e.g 1 above

$ev = array('2', '4', '6', '8', '10', '12');

foreach($ev as $a)
{
if($a % $div != 0)
/*Since it will return 0 for our unwanted 6 and 12*/
{
if($counter > 0)
{
echo ', '; //As explained in e.g 1 above
}
echo $a;
$counter++; //As explained in e.g 1 above.
}
}
?>


The above returns:
/*From E.g 1 */

2, 4, 8, 10

/*From e.g 2 */

2, 4, 8, 10
Re: PHP Simple Puzzle by omni1(op): 4:21pm On Apr 14, 2013
Please how can we get more beginners here to learn? Now they are seeing trials and how codes are being ran and thanks to all for the inline commenting which is helping so much. It's a good practice coding with inline commenting so that anyone at your absence can maintain your codes. Please let's get more beginners to come along and test their abilities.

Thanks to other friends who have supported in the puzzle posting and resolutions. I'm very very grateful. Some little engagements holding offline but I'll post other simple puzzles as well as assist in testing and picking correct answers as soon as I'm done.

Cheers Friends!
Re: PHP Simple Puzzle by omni1(op): 4:28pm On Apr 14, 2013
Gerardcole: I usually type on my android device so sorry for the errors. I didn't close a line with ;. Also I didn't close the if containing the in_array(), then I interchanged the position of the values in in_array. So editing the former post, here is the solution.


Okay. Since according to our puzzle provider, Judinho59 didn't get the required output, I ll provide my own solution. The puzzle is kinda tricky.

Given array('2', '4', '6', '8', '10', '12')
To return 2,4,8,10 (Removing 6 and 12 and the last comma that's supposed to appear after 10)

I'm also gonna attack in two methods.

1. Using PHP in_array()

<?php
/* First we set the values we do not want in an array */
$unwanted = array('6', '12');

/*Then we set a variable which will help in placing comma's */

$counter = 0;

/*Then to the code */
$ev = array('2', '4', '6', '8', '10', '12');

foreach($ev as $a)
{
if(!in_array($a, $unwanted))
/*Checks if $a is not in our unwanted list before proceeding*/
{
if($counter > 0)
/* Since we don't want it after our last value but after every other, we run this before the value. > 0 here explains that we don't want it before the first as our counter is still 0 before this line */
{
echo ', ';
}
echo $a;
$counter++;
/*In PHP ++ is same as +1 so whenever it gets to the line above, the counter is increased buly 1*/
}

}
?>

2. Using the modulus operator '%'

The modulus %, in PHP returns the remainder in a division operation. E.g 7 % 5 returns 2 (i.e 1 remaining 2), 10 % 5 returns 0 (i.e 2 remaining 0).

I wouldn't be explaining the lines I already explained in example 1 above.

<?php
$div = 6;
/* Since all the unwanted numbers are divisible by 6. */

$counter = 0; //As explained in e.g 1 above

$ev = array('2', '4', '6', '8', '10', '12');

foreach($ev as $a)
{
if($a % $div != 0)
/*Since it will return 0 for our unwanted 6 and 12*/
{
if($counter > 0)
{
echo ', '; //As explained in e.g 1 above
}
echo $a;
$counter++; //As explained in e.g 1 above.
}
}
?>


The above returns:
/*From E.g 1 */

2, 4, 8, 10

/*From e.g 2 */

2, 4, 8, 10
Code runs fine as expected. Nice dual solution!

I'm also thinking TRIM should be brought into light here so that the awareness of the different types of TRIMS could be seen and used too.
http://php.net/manual/en/function.trim.php
Re: PHP Simple Puzzle by Nobody: 4:58pm On Apr 14, 2013
ActiveMan: <?php
$even_numbers = array('2','4','6','8','10','12');

$remove_12_6_from_array = array_diff($even_numbers , array('6', '12'));

echo $even_numbers = implode ( "," , $remove_12_6_from_array );

?>

YOU DO NOT NEED ANY LOOP.
Cool.By using loops instead of functions,we make the puzzle more interesting.


Judinho59:

<?php
$even_numbers = array('2','4','6','8','10','12');
$arr = array();
$out = array('6','12');
foreach($even_numbers as $value) {
if(!in_array($value, $out)){
$arr[] = $value;
}
}
$value = implode(",", $arr);
echo $value;

?>


Result:
2,4.8,10

Excellent!


Gerardcole: <?php
/* First we set the values we do not want in an array */
$unwanted = array('6', '12');

/*Then we set a variable which will help in placing comma's */

$counter = 0;

/*Then to the code */
$ev = array('2', '4', '6', '8', '10', '12');

foreach($ev as $a)
{
if(!in_array($a, $unwanted))
/*Checks if $a is not in our unwanted list before proceeding*/
{
if($counter > 0)
/* Since we don't want it after our last value but after every other, we run this before the value. > 0 here explains that we don't want it before the first as our counter is still 0 before this line */
{
echo ', ';
}
echo $a;
$counter++;
/*In PHP ++ is same as +1 so whenever it gets to the line above, the counter is increased buly 1*/
}

}
?>

<?php
$div = 6;
/* Since all the unwanted numbers are divisible by 6. */

$counter = 0; //As explained in e.g 1 above

$ev = array('2', '4', '6', '8', '10', '12');

foreach($ev as $a)
{
if($a % $div != 0)
/*Since it will return 0 for our unwanted 6 and 12*/
{
if($counter > 0)
{
echo ', '; //As explained in e.g 1 above
}
echo $a;
$counter++; //As explained in e.g 1 above.
}
}
?>


The above returns:
/*From E.g 1 */

2, 4, 8, 10

/*From e.g 2 */

2, 4, 8, 10
Impressive!
Re: PHP Simple Puzzle by Nobody: 5:02pm On Apr 14, 2013
NEW PUZZLE

Create an infinite loop of all even numbers.



You may post more than one answer.
N.B.I will not be responsible for any system malfunction during testing!
Re: PHP Simple Puzzle by omni1(op): 5:18pm On Apr 14, 2013
Web Contractor:
N.B.I will not be responsible for any system malfunction during testing!
Hahahahaaa...... You sure know browsers will hang abi?
Re: PHP Simple Puzzle by Nobody: 5:37pm On Apr 14, 2013
i will not run your puzzle but this is infinite loop in action


<?php
for (;; ) {
print "infinite loop!\n";
}
?>

<?php
while(1) {
print "infinite loop!\n";
}
?>
Re: PHP Simple Puzzle by Gerardcole(m): 5:42pm On Apr 14, 2013
Just remembered that while(1). Nice one active man. I have already followed another approach.

I had an error in my codes while coding that made a condition always true. I know how hard it took me to even close my browser and restart. So I'm not testing this but will give a snippet.

<?php
$cond = 1;
/*Sets a variable that will aid in looping.*/

$even = 2; //Even no's are divisible by 2 without remainder.

$number = 0; //First number

while($cond == 1)
/*Since is already 1, this condition will never end*/
{
if(($number % $even == 0) AND ($number != 0))
/* Since it will return same for 0 but we don't want 0 */
{
echo $number.', ';
}
$number++;
}
?>
Re: PHP Simple Puzzle by omni1(op): 6:02pm On Apr 14, 2013
To test the codes to a certain number limit, you can add an extra condition to be at least sure only even numbers are displayed. Taking a lead from @Gerardcole's codes

Gerardcole: <?php
$cond = 1;
/*Sets a variable that will aid in looping.*/

$even = 2; //Even no's are divisible by 2 without remainder.

$number = 0; //First number

while($cond == 1)
/*Since is already 1, this condition will never end*/
{
if(($number % $even == 0) AND ($number != 0))
/* Since it will return same for 0 but we don't want 0 */
{
echo $number.', ';
}
$number++;
}
?>
Add in:
if(($number % $even == 0) AND ($number != 0) && ($number <= 200)
To get even numbers from 0 - 200.

You'll experience Maximum execution time limits depending on your php.ini maximum execution time set if you run the infinite loop and your time limit is reached.
Re: PHP Simple Puzzle by Nobody: 6:07pm On Apr 14, 2013
NEW PUZZLE
given this table from your database

dbname: ssCompant
dbuser: delti
dbpass: dkiiri84

table name: debtors

id=====username======amount
1======serelat======2000
2======bukkyer======4587
3======walex========8955
4======adaame=======9874
5======nomoney======1000


connect to this database and use a while loop to display this information.
Re: PHP Simple Puzzle by omni1(op): 6:19pm On Apr 14, 2013
@ActiveMan
Please let's not get into the DB aspect now. I still think we just keep playing around with strings and integers. I wonder how many of them are even taking note. No questions yet. I guess we should allow for like up to 5 answers if possible to be sure that people are following up before we declare answers then put up a new puzzle. Some might just come along, see and copy solutions without even knowing how they were solved.
Re: PHP Simple Puzzle by Gerardcole(m): 6:23pm On Apr 14, 2013
<php
$db = new mysqli( 'localhost' , 'delti' , 'dkiiri84' , 'ssCompant' );

$q = $db->query("SELECT `username`, `amount` FROM `debtors`"wink;

while($grab = $q->fetch_assoc())
{
echo $grab['username'].': $'.$grab['amount'].'<br>';
}
?>

Output:

serelat: $2000
bukkyer: $4587
walex: $8955
adaame: $9874
nomoney: $1000

/*Not Tested*/
Re: PHP Simple Puzzle by Nobody: 6:36pm On Apr 14, 2013
$sql_conn = mysql_connect("localhost", "delti", "dikiiri84"wink or die(mysql_error());
if(!$sql_conn) echo "Mysql Error:".mysql_error();
if(!mysql_select_db("ssCompant",$sql_conn))
die(mysql_error()));

while($result = mysql_fetch_object(mysql_query("SELECT * FROM debtors ORDER BY id DESC"wink){
echo"".$result->id.": " . $result->username . " = " . $result->amount. "";
}

Result:
1: serelat = 2000
2: bukkyer = 4587
3: walex = 8955
4: adaame = 9874
5: nomoney = 1000
Re: PHP Simple Puzzle by Nobody: 6:37pm On Apr 14, 2013
*omni:
@ActiveMan
Please let's not get into the DB aspect now. I still think we just keep playing around with strings and integers. I wonder how many of them are even taking note. No questions yet. I guess we should allow for like up to 5 answers if possible to be sure that people are following up before we declare answers then put up a new puzzle. Some might just come along, see and copy solutions without even knowing how they were solved.
Seconded!!
Re: PHP Simple Puzzle by omni1(op): 6:41pm On Apr 14, 2013
Can we do something here....

Let's benchmark our codes for faster running. If you run the codes by @Gerardcole on the Infinite loop puzzle, you'll see it takes some time to output results. You can compare this other variation to understand what I mean. Speed of result output is of essence in our codes as well.

<?php
for($a = 1; $a <= 500;$a++){
if($a % 2 == 0) echo $a,',';
}
?>
Run this other one still not exceeding 500

<?php
$cond = 1;
/*Sets a variable that will aid in looping.*/

$even = 2; //Even no's are divisible by 2 without remainder.

$number = 0; //First number

while($cond == 1)
/*Since is already 1, this condition will never end*/
{
if(($number % $even == 0) AND ($number != 0) AND ($number <= 500))
/* Since it will return same for 0 but we don't want 0 */
{
echo $number.', ';
}
$number++;
}
?>
After running for 500, change to 100000 and see what happens still.

Do you notice any variation in their processing speed? That's something I'll also like us to look into while providing solutions for the puzzles.
Re: PHP Simple Puzzle by omni1(op): 7:16pm On Apr 14, 2013
Web Contractor: NEW PUZZLE

Create an infinite loop of all even numbers.



You may post more than one answer.
N.B.I will not be responsible for any system malfunction during testing!
<?php
#set $a start count from 1
#set $a to be greater than 0 ($a > 0) so as to be infinite since original value = 1
#increment $a at every point in time $a is greater than 0 (infinite)
#to get even numbers, divide the output of $a and ensure no remainder ie ($a % 2 == 0)
#print your output (echo $a) append a comma and space after it for clearer reading (echo $a, ', ')

/*
For faster concatenation, I'll suggest you implore the use of comma to a dot.
*/

for($a = 1; $a > 0; $a++){
if($a % 2 == 0) echo $a, ', ';
}
?>

Set stop watch to like 2 minutes and stop code execution to see the numbers it has looped through. Don't let your browser hang anyways.
Re: PHP Simple Puzzle by Nobody: 8:45pm On Apr 14, 2013
Whats Next?? grin
Re: PHP Simple Puzzle by omni1(op): 9:20pm On Apr 14, 2013
Create a program that will print out all factors of 7 between 1 and 1000. Each number should be on a separate line.
Hint: use modulus!

Level: Beginner
Re: PHP Simple Puzzle by Gerardcole(m): 9:47pm On Apr 14, 2013
<?php
/*
/*My eyes are already closing Henri saw this so less comments
/*Its same for loop you used above that would be applied with modulus.
*/
for($a = 1; $a >= 1000; $a++)
{
if($a % 7 == 0) echo $a.'<br>';
}
?>

/*Not Tested*/
Re: PHP Simple Puzzle by Nobody: 10:36pm On Apr 14, 2013
Gerardcole: <?php
/*
/*My eyes are already closing Henri saw this so less comments
/*Its same for loop you used above that would be applied with modulus.
*/
for($a = 1; $a >= 1000; $a++)
{
if($a % 7 == 0) echo $a.'<br>';
}
?>

/*Not Tested*/
Thumbs!!
Re: PHP Simple Puzzle by omni1(op): 3:46am On Apr 15, 2013
@Gerardcole, @Judinho59 Please ooooo... You should stop answering so the beginners will at least try out their hands on the questions before they are corrected with some methods of solving the puzzles. Let's give them a chance to try their hands on the puzzles
Re: PHP Simple Puzzle by omni1(op): 4:33am On Apr 15, 2013
<?php
$array[0] = "mall";
$array[1] = "Kate";
$array[2] = 9;
$array[3] = "brother";
$array[4] = "cup cakes";
$array[5] = "store";
$array[6] = "Linda";

echo "$array[1] went to the $array[0] to buy $array[2] $array[4] for her $array[3].";
?>

From the above PHP scripting block, what will be displayed in the browser?

Level: Intermediate.
Re: PHP Simple Puzzle by Nobody: 10:00am On Apr 15, 2013
*omni:
@Gerardcole, @Judinho59 Please ooooo... You should stop answering so the beginners will at least try out their hands on the questions before they are corrected with some methods of solving the puzzles. Let's give them a chance to try their hands on the puzzles
iThink u're right.. cheesy
Re: PHP Simple Puzzle by omni1(op): 1:14am On Apr 17, 2013
Hmmm..... doesn't seem they are interested in our quiz. So what do we do? Our help isn't going down well with them from what I see here. What do you guys think?
Re: PHP Simple Puzzle by tamilgt: 12:14pm On Jul 15, 2013
Code For to change from " array(2,4,6,8,10,12) " to 2,4,8,10:

Input :
$even_numbers = array(2,4,6,8,10,12);

foreach($even_numbers as $en) {

if($en%6!=0){
$even_numbers_res.=$en.',';
}

}

echo substr($even_numbers_res,0,-1);

Output:
2,4,8,10
Re: PHP Simple Puzzle by omni1(op): 3:58pm On Jul 17, 2013
I think we might continue with this to see how many people will along and play with codes but basically beginners except if the question level specifies otherwise.
Re: PHP Simple Puzzle by Nobody: 5:20pm On Jul 17, 2013
*omni:
I think we might continue with this to see how many people will along and play with codes but basically beginners except if the question level specifies otherwise.
Yezzir! smiley
Re: PHP Simple Puzzle by romme2u: 12:38am On Jul 18, 2013
Gerardcole: Can explain in words:

$a == $b; //$a and $b are equal. True.

$a !=== $b; //$a and $b are not identical. True

E.g:

<?php
$a = 0;
$b = 000;
if($a == $b)
{
echo '$a and $b are equal';
} else {
echo '$a and $b are not equal';
}
echo '<br>';
if($a === $b)
{
echo '$a and $b are identical';
} else {
echo '$a and $b are not identical';
}
?>

The code above will output:

$a and $b are equal
$a and $b are not identical
u could have used the ternary operator to reduce ur lines of code
suggestion anyway
1 2 3 Reply

Web Masters Please Help Me Solve This PuzzleI Challenge The Level Of Intelligence On This Forum With This Puzzle.234

Basic Tips To Protect Your Website From Hackers16 Mistakes That Turn People Away From Your WebsitePaid Dating Sites Available For Sale