Log in

View Full Version : Enum arrays



dcr33
08-31-2012, 05:08 AM
<?php
$myarray = array(
[0] => 'string a',
[2] => 'string b',
[4] => 'string c',
[8] => 'string d',
);
$arraycount = count( $myarray );
for( $i = 0; $i < $arraycount; $i++ ) {
echo 'key is: ' . $i . ' - value is ' . $myarray[$i] . '<br />';
}
?>
Why is the above code showing error as follows:
Parse error: syntax error, unexpected '[', expecting ')' in ....\xampp\htdocs\....\1.php on line 3

djr33
08-31-2012, 05:18 AM
[8] => 'string d',

dcr33
08-31-2012, 06:13 AM
But that is already in the code
[8] => 'string d', Where is the error?

djr33
08-31-2012, 07:05 AM
The last item in an array (or any other kind of comma separated list) must NOT have a comma, or it will cause an error.

By the way you're going to get a lot of warnings about undefined indices if you do it like that. You'd need to count by two in the for loop, or you could use a foreach loop, which is specifically designed for arrays.

dcr33
08-31-2012, 07:12 AM
Ya i intentionally put those indices like that. ;-) :-P But i removed the last comma still it i giving error

dcr33
08-31-2012, 07:13 AM
I put it like this according to your suggestion@djr33,but still i get the same error!

<?php
$myarray = array(
[0] => 'string a',
[2] => 'string b',
[4] => 'string c',
[8]=> 'string d');
$arraycount = count( $myarray );
for( $i = 0; $i < $arraycount; $i++ ) {
echo 'key is: ' . $i . ' value is ' . $myarray[$i] . '<br />';
}
?>

djr33
08-31-2012, 07:31 AM
Oh, you don't put [] around array keys. That's just when it's being displayed to you (such as with the print_r() function), or when you are accessing an individual item from the array with $array[0] or $array['key'].


<?php
$myarray = array(
0 => 'string a',
2 => 'string b',
4 => 'string c',
8=> 'string d');
$arraycount = count( $myarray );
for( $i = 0; $i < $arraycount; $i++ ) {
echo 'key is: ' . $i . ' value is ' . $myarray[$i] . '<br />';
}
?>

dcr33
08-31-2012, 07:38 AM
Ohh Thanks I overlooked that!!
:-P

dcr33
08-31-2012, 07:39 AM
Thanks for helping..I overlooked that

rinumathew
08-20-2014, 06:56 AM
Please try the below code

<?php
$myarray = array(
0 => 'string a',
2 => 'string b',
4 => 'string c',
8 => 'string d',
);

foreach($myarray as $x=>$x_val)
{
echo 'key is: ' . $x . ' - value is ' . $x_val . '<br />';
}
?>

Deadweight
08-20-2014, 01:15 PM
I am not sure why you posted this but here is a little help:
example 1: Enum Object


<?php

class enum {
const data1 = 0;
const data2 = 1;
const data3 = 2;
//etc...
}

print enum::data2;
//prints '1'
?>


or

Example 2: Array


<?php
$dataset = array();
$dataset[] = 'Sunday';
$dataset[] = 'Monday';
$dataset[] = 'Tuesday';
$dataset[] = 'Wednesday';
$dataset[] = 'Thursday';
$dataset[] = 'Friday';
$dataset[] = 'Saturday';
$datasetenum = array();
foreach( $dataset as $key => $val ){
$datasetenum[$val] = $key;
}
print $datasetenum['Tuesday']; //prints '2'
print $datasetenum['Friday']; //prints '5'
?>