Vahid Najafi
Vahid Najafi

Reputation: 5263

How can I make an array dynamically in php?

In the below code the repetition of foreach is unknown. It depends on database records.

<?php
$i = 0;
        foreach ($get_all_users as $row){                    
                echo $name[$i] = $row->name;
                $i++;
        }
?>

Now, in below, I want to make an array dynamically, as many as foreach repetition. But I can't add any loops into array:

$i = 0;
$data['name'] = array (                     
    $i => $name[$i],                     
);

Actually, I need something like this: (of course it's impossible)

$i = 0;
$data['name'] = array (
    for(...)                    
    $i => $name[$i],
);

Thank you very much.

Upvotes: 1

Views: 84

Answers (4)

bodruk
bodruk

Reputation: 3262

UPDATE Attending your comment...

$data['name'] = array(); 
foreach($get_all_users as $row){ 
    array_push($data['name'], $row->name);
}

Upvotes: 2

Mark
Mark

Reputation: 125

Perhaps this:

$data = array_column($get_all_users, 'name');

is what you need. It's a little unclear....

Upvotes: 0

Abdessabour Mtk
Abdessabour Mtk

Reputation: 3888

you don't need to use two loops only one like this :

$data['name'] = array();

foreach ($get_all_users as $row){                    
            $data['name'][] = $row->name;
}

Upvotes: 1

daxur
daxur

Reputation: 359

You just need to define an blank array and then put values into it with empty "index".

Something like this:

$names = array();
foreach ($get_all_users as $row){                    
  $names[] = $row->name;
}

Upvotes: 1

Related Questions