iwan iwan - 5 months ago 20
PHP Question

PHP version differences of arrays

I am having some problems with the different versions of PHP arrays. I am creating a custom portfolio page for a wordpress theme and it works perfectly on localhost using the latest PHP version. However when I wanted to try it online I got an error:


Parse error: syntax error, unexpected '[', expecting ',' or ';' in /wordpress/wp-content/themes/theme/functions.php on line 72


The server is running a PHP version 4.0.10.14 and I need to install the portfolio to there. Is there any way to convert this line to be compatible with the old PHP version however still possible to use it in latest PHP versions?

<img src="<?php echo get_post_meta(get_the_ID(), 'portfolio_imgs',
true)[$i]['url']; ?>" width="96" height="54"/>


Here is the complete section of the code:

$portfolio_array = get_post_meta(get_the_ID(), 'portfolio_imgs', true);
$arrlength = count($portfolio_array);
for ($i=0; $i<$arrlength; $i++) {
?>
<div class="uploaded_images" id="image_<?php echo "$i" ?>"
onClick="delete_image(<?php echo $i; ?>)">
<img src="<?php echo get_post_meta(get_the_ID(), 'portfolio_imgs',
true)[$i]['url']; ?>" width="96" height="54"/>
<input type="hidden" id="id<?php echo $i ?>" name="selection[]" value="keep"/>
</div>
<?php
}
?>

Answer

Assuming your get_post_meta() function returns a valid array, then the following should work:

$result = get_post_meta(get_the_ID(), 'portfolio_imgs', true);
<img src="<?php echo $result[$i]['url']; ?>" width="96" height="54"/>

Your current version is using what is called "Function array dereferencing" which was introduced in PHP 5.4.

Comments