Archive

Posts Tagged ‘program’

Swapping variable values in PHP [Short post]

October 11, 2013 No comments

Yesterday we talked about swapping variables in C and C++. This time, we will do it in PHP.

We can translate the C program to PHP, creating a temporary value and running the program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
$a = 11;
$b = 99;

echo "Original A value: ".$a."\n";
echo "Original B value: ".$b."\n";

$tmp = $a;
$a = $b;
$b = $tmp;

echo "New A value: ".$a."\n";
echo "New B value: ".$b."\n";
?>

It will simply work, but we can take advantages of built-in PHP functions, to make it shorter (and we won’t use a temporary variable):

1
2
3
4
5
6
7
8
9
10
11
12
<?php
$a = 11;
$b = 99;

echo "Original A value: ".$a."\n";
echo "Original B value: ".$b."\n";

list($a, $b) = array($b, $a);

echo "New A value: ".$a."\n";
echo "New B value: ".$b."\n";
?>

So first we create an array with values $b and $a and then we separate this values in variables $a and $b. The result is the same.

Hello world!

October 9, 2013 1 comment

Not just WordPress’ default post title. As a programmer, I’ve written hundreds of “hello world” programs to test compilers, to test libraries, to test new programming languages… that’s an easy way to know things work and to know I can make it work.

I will write here about programming (my favourite languages are C, C++ and PHP, so I will talk about them. Maybe I’ll write something about another languages too); Unix-like operating systems, I use GNU/Linux everyday and I really like the way it works and how customizable it is (but most things are applicable to other *nixes).

So I welcome youto my new blog, hoping you find it useful, and leave some comments here, and share my posts if you like them.

 

Photo: Angel Raul Ravelo Rodriguez (Flickr) Licensed: CC-by.

3XBU27AYR3ZJ code for Technorati

Top