2 Replies - 9816 Views - Last Post: 30 December 2011 - 02:17 AM Rate Topic: -----

#1 falcon24  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 16
  • Joined: 10-June 11

how to create a two dimensional array

Posted 29 December 2011 - 10:26 PM

hi! i just want to know how to create a two dimensional array of objects.
I have a code here that is written in java,but i don't how to convert this into php.
Here is the code : private Cell[][]cell = new Cell[15][15];
Is This A Good Question/Topic? 0
  • +

Replies To: how to create a two dimensional array

#2 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10826
  • View blog
  • Posts: 40,363
  • Joined: 27-December 08

Re: how to create a two dimensional array

Posted 29 December 2011 - 11:37 PM

PHP isn't strongly typed. Arrays in PHP can store elements of multiple types. If you want to store objects of class Cell in an array, just instantiate one in the array. The basic syntax for creating an array in PHP is:
$arr = array();
$twoD = array(array());



More on arrays.

Quote

I have a code here that is written in java,but i don't how to convert this into php.

Rather than focusing on converting code, focus on learning PHP. You'll get a better grasp on the language's intricacies than if you focus on converting from Java.
Was This Post Helpful? 3
  • +
  • -

#3 e_i_pi  Icon User is offline

  • = -1
  • member icon

Reputation: 801
  • View blog
  • Posts: 1,700
  • Joined: 30-January 09

Re: how to create a two dimensional array

Posted 30 December 2011 - 02:17 AM

macosxnerd101 gives some good advice here regarding learning PHP rather than converting code. Each language has it's strengths and it's weaknesses, and if you try a straight conversion of syntax, you'll likely miss out on some of the key features of the language you're converting to, and carry over some incompatible features of the language you are converting from.

As far as instantiating and populating arrays goes, here's a few examples...
// Non-associative (numeric) array
$ary1 = array();
$ary1[] = '!Hello';
$ary1[] = ' World!';
echo '$ary1 contents: ' . $ary1[0] . $ary1[1];

echo '<br>';

// Associative array
$ary2 = array();
$ary2['a'] = '@Hello';
$ary2['b'] = ' World@';
echo '$ary2 contents: ' . $ary2['a'] . $ary2['b'];

echo '<br>';

// Multi-dimensional array, with mixed associative and non-associative
$ary3 = array();
$ary3[] = array();
$ary3[0][] = '#Hello';
$ary3[] = array();
$ary3[1]['World'] = ' World#';
$ary3[] = array(' Goodbye', 'Final' => ' Cruel World');
echo '$ary3 contents: ' . $ary3[0][0] . $ary3[1]['World'] . $ary3[2][0] . $ary3[2]['Final'];


Was This Post Helpful? 3
  • +
  • -

Page 1 of 1