GIDNetwork > Porting code from C++ to PHP
« A Random Dispersion Array - C++ console Changing Client Side Memory Values Using TSearch »

Porting code from C++ to PHP

by: cable_guy_67 - Aug 03, 2005

Chapter Two : Random Dispersion Array PHP

Now that there is some working (C++) code that shows how to create a random dispersion array it is time to make the crossing. Perhaps this was how the explorers felt when sailing into the unknown. They knew how to sail, but didn't know what was in store for them over the horizon. Well, even if they didn't, it's sure how I felt.

Before we leave the relative safety of the harbor, let's take a look at what we hope to discover.

The Brave New World.

That is the land of wonder that I hope to find. That is what got my excitement level up. That is what I will dream of on the long journey across the metaphorical sea. Like any trip there will be pitfalls and detours that need to be made. Perhaps we will have to disassemble the ship and carry it over the mountains, rebuilding it when a new body of water is discovered. Perhaps we will need a different type of vessel, and the ship will become lumber for our new homes. These things can be imagined but not known yet on our journey. What we really need to do is put up some supplies that we may need along the way.

Since we are decidedly eclectic group lets use a broad brush when we pick up navigational tools. I'm sure that that will not be all we need so lets throw in this, a bit of that, a few things from here and as much as we can carry from here. Now, we don't want to lose track of our friends back home so let's sit this right on top of the pile. After all, we don't want to forget our roots. Or how to get home if we need to. :)

Okay, we are loaded down. Some things we will use all the time, some we will only need on special occasions. There are things we have that we don't even know how to work yet, but we can learn. So we wave to the single person viewing and look forward...

FILE : rand_prob_func.php

The first thing we are going to do is wrap our code up so there is no doubt what we are working with. To do this, you start with <?php, give yourself some lines to work with and close with ?> somewhere below. This is considered a single PHP block. There will be times when it is important to start and finish things, all in one block. You may also have multiple blocks in your file. For now though, treat it like the C++ statement,

C/CPP/C++ Code Example:

using namespace std;

when you were first starting out. You might not have known exactly what it was doing, but eventually you figured out that it needed to be there. We also will be using some comments to start our file just like we did with the C++ version. In PHP, you can use your old friends from C++ as well as the pound sign.

PHP Code Example:

// A single line comment

 *  A multi-line comment

# another single line comment

From the manual:

PHP supports 'C', 'C++' and Unix shell-style (Perl style) comments.
The "one-line" comment styles only comment to the end of the line or the current block of PHP code, whichever comes first.

Now we can get the information block at the start of the file done. I will be using the C style multi-line block since with a little modification, it will become something that is special when using Doxygen, a very cool documentation system, but I digress. For now, just remember the ways you can add comments to your code.

PHP Code Example:


  * rand_prob_func.php
  * copyright © 2005 Mark Roth Nescopeck PA
  * MRothCode[at]gmail[dot]com
  * No warranty, no nothing.  If you don't like it, don't run it.
  * If you do, use it in any way your imagination can come up with.
  * Building a random probability array to display Advertising
  * publisher ID code on a case by case basis.


As you can see, except for the opening PHP tag, this would have worked without modification in C++.

Error Reporting in PHP

This was one of the first problems I ran into when starting out with the C++ to PHP conversion. I missed my compiler. I use -Wall whenever I compile code. One of the first pieces of PHP code I wrote would have made g++ punch me in the forehead a few times before drinking all my beer for being an idiot. Luckily, there is a way to get information on code that just shouldn't be allowed to be run. Because it will, oh it will, but you may not like the results.

PHP Code Example:


  error_reportingE_ALL );


From the manual:

int error_reporting ( [int level] )

The error_reporting() function sets the error_reporting directive at runtime. PHP has many levels of errors, using this function sets that level for the duration (runtime) of your script.

There are many, many things that can be set or unset. You will need to do a little research but the ones I have set up seem to give me a nice level of error message reporting echoed to the page being rendered. They come complete with filename and line numbers so you can track things down just like you would from your compiler errors/warnings.

Random Number Generation C++ vs. PHP

In the C++ program there were three items for the generation of random numbers. They were,

C/CPP/C++ Code Example:

static bool seeded
void RNDseed()
const unsigned RNDgen(const unsigned MAX)

We don't need these in PHP. Instead use mt_rand().

From the Manual:

int mt_rand ( [int min, int max] )

Many random number generators of older libcs have dubious or unknown characteristics and are slow. By default, PHP uses the libc random number generator with the rand() function. The mt_rand() function is a drop-in replacement for this. It uses a random number generator with known characteristics using the Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.

If called without the optional min, max arguments mt_rand() returns a pseudo-random value between 0 and RAND_MAX. If you want a random number between 5 and 15 (inclusive), for example, use mt_rand (5, 15).

FUNCTION : GetPer100() and GetMagic100() Integer Math

PHP Code Example:


 *  $DefPercent is the default ID percentage of showing
 *  $OtherIDs is the number of other publisher IDs to be concerned with.
 *  returns a count less than or equal to 100.  It is the per/100 number.
 *  It will be used to compute an even integer percentage for fairness.

function GetPer100$DefPercent$OtherIDs){
  return $DefPercent + ((int)((100 $DefPercent) / $OtherIDs) * $OtherIDs );

 *  $Per100units is the integer amount returned by GetPer100
 *  $OtherIDs is the number of other publisher IDs to be concerned with.
 *  returns an integer for use in computing the actual numbers per array
 *  instances that will equal a given percentage.  It also can be
 *  multiplied by 100 to get the actual arrray size needed.

function GetMagic100$Per100units$OtherIDs ){

  $magic100 0;
  $per100remain 100 $Per100units;

  for( $magic100 1; (( $per100remain $magic100) % $OtherIDs) != 0$magic100++ );

  return $magic100;


These two functions work identically to their C++ counterparts. The major difference is PHP's lack of an unsigned integer type. Because of this, a cast in GetPer100() is needed to keep the results from being promoted to a float. Looks like a familiar C cast to me. It is something to keep in mind when working with PHP's loose typing. There will be times (like this one) that you will need to specify your results since you can't declare the variable as a particular type. Remember to use the '$' with the variables and this type of covertion goes smooth.

FUNCTION : BuildRndList() Randomized Weighted List

PHP Code Example:

 *  $IDarray is the array that holds indexes to the publisher ID code array
 *    for testing it will refer to a global array and take a reference to it
 *  $size is an integer that is the actual size of the final index array.
 *  $OtherIDs is the number of additional publisher IDs to be concerned with.
 *  $OtherIDamt is the number of units per final array for additional publishers.
 *  This works on the actual array that will be used of size $size that is passed
 *  by reference to BuildRndList.  Does not return until the array is complete.

function BuildRndList( &$IDarray$size$OtherIDs$OtherIDamt ){

  $rndASpubID array_fill0$size);
  for ( $i 1$i <= $OtherIDs$i++ ) {
    for ( $j 0$j $OtherIDamt$j++) {
      $loop true;
        $RNDnum mt_rand0$size 1);
        if ( $IDarray[$RNDnum] == ) {
          $IDarray[$RNDnum] = $i;
          $loop false;
      }while ( $loop );


Once again, this is nearly a verbatim translation from C++. The biggest difference is using mt_rand() instead of the custom routines that were in the C++ version and array_fill() to zero the array.

FILE : rand_global_setup() to simulate C++ main()

Since I am breaking this down into smaller and smaller units as I go, the main() testing routine from the first chapter is now it's own code module. In will be part of the next chapter that will also describe a simple HTML form to use for display purposes. In it, you will find the syntax that PHP uses to create an array(). That will be the last of the C++ to PHP chapters and should give C++ programmers enough to see the similarities and differences.

To any PHP programmers out there: please comment if I have made any glaring errors. I am teaching myself as I go so it is quite possible I have made an errror or two. Hold tight, I am going to toss many of the extra planned chapters in favor of moving more directly to the PHP Extention with dl() portion of the show.

Update from Table of Contents. This series will be shortened and the next chapter will be the last "C++ to PHP" article. After that, the focus will be on using this code (or your own code) to create a PHP extention. Once I have that down, I will be able to tackle using C++ code then classes as a PHP extension.

  • Chapter 3 - using HTML forms to display the array and previously descibed as chapter 3 and 4

  • Chapter 4 - Building a PHP extension

  • Chapters 5, 8 and 10 will be deleted

Would you like to comment? This story has been viewed 24,067 times.
« A Random Dispersion Array - C++ console Changing Client Side Memory Values Using TSearch »


Copyright © GIDNetwork™ 2001 - 2018

Another website by J de Silva

Page generated in : 0.01111 sec.