0

I'm looking for a way to optimize the following code using while loop.. I've got 4 arrays and would like to pull the 1st value from each array in the most efficient way. This is the original code which works fine:

$arr1 = array ("55", "66", "77");
$arr2 = array ("54", "64", "771");
$arr3 = array ("53", "62", "772");
$arr4 = array ("52", "60", "773");
$x = 1;
$result = "null";

echo $arr1[0] . " | " ; 
echo $arr2[0]. " | " ; 
echo $arr3[0]. " | " ; 
echo $arr4[0]. " | " ; 

Blow is my attempt to optimize it but it doesn't seems to be working:

$arr1 = array ("55", "66", "77");
$arr2 = array ("54", "64", "771");
$arr3 = array ("53", "62", "772");
$arr4 = array ("52", "60", "773");
$x = 1;
$result = "null";

while($x < 5) {
$result = "$arr".$x."[0]";
echo $result;
echo " | ";
$x = $x +1;
}

The output I'm getting is 1[1] | 2[1] | 3[1] | 4[1]
Instead of 55 | 54 | 53 | 52 |

Thank you all!

2 Answers 2

4
while($x < 5) {
    $result = ${"arr".$x}[0];
    echo $result;
    echo " | ";
    $x++;
}

or a neater solution:

$arr1 = array ("55", "66", "77");
$arr2 = array ("54", "64", "771");
$arr3 = array ("53", "62", "772");
$arr4 = array ("52", "60", "773");

for($x=1; $x<5; $x++) {
    $result = ${"arr".$x}[0];
    echo $result." | ";
}
Sign up to request clarification or add additional context in comments.

1 Comment

${"arr" . $x}is the correct answer to call a automatic generated variable name. look at the example above
1

"One-line" solution using call_user_func_array and array_column functions:

$result = implode(" | ", call_user_func_array('array_column', [[$arr1, $arr2, $arr3, $arr4], 0]));

print_r($result);

The output:

55 | 54 | 53 | 52

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.