PHP array inside foreach loop

Hello experts,

how's that $author[] assigment in foreach loop work? I understand that It's an array of assosiated arrays, but there's no $authors[] = array(); before in code, so it's some kind of shortcut to create an array with empty [] added right to variable's name?

I'm confused with that, because when you echoing it to the page you use
foreach ($authors as $author) {.... } without the [], so that would mean that it's an shortcut for array creation? $nameOfArray[]; ??
 
try {  $result = $pdo->query('SELECT id, name FROM author'); }

foreach ($result as $row)
{
	$authors[] = array('id' => $row['id'], 'name' => $row['name']);
}

Open in new window

LVL 1
Fajer39Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Marco GasiFreelancerCommented:
In Php you don't necesaily need to declare an array this way:
$authors = array();

Open in new window

even if I think it could be better to avoid unexpected errors. Anyway you can just create the array within the loop: when you write
$authors[] = ...

Open in new window

you're just adding an element to an array and the brackest tell Php 'Hello, I'm an array so add this element to me!'. So, yes, we can say that notation is a "shortcut for array creation".

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ray PaseurCommented:
The empty square brackets are a "new" array notation for PHP - much like the JavaScript notation.  This makes sense, given the way web sites and applications are made today, with increasing reliance on JavaScript for front-end automation.  The PHP part of things is more frequently relegated to a background role - just returning JSON from a server.

A try{} block around a PDO query should have a catch{} block associated with it.  If you try{} a query, you might also process the query results set inside the try{} block.
http://php.net/manual/en/language.exceptions.php
http://php.net/manual/en/class.pdoexception.php

In the instant case, I do not think you need anything more than try{} and catch{}.  It does not make sense to copy the results set into a separate array.  I think what you need is already available with named keys in the $result variable.
Fajer39Author Commented:
@Ray Paseur: I know but I would expect $array = []; not $array[]; that's why I asked.

Thanks.

@Ray Paseur, @Marco Gasi: It's an example from chapter07(CMS) from PHP: Novice to Ninja, the book that you guys recommended me a couple days back. So I know there should be a catch and in my code it sure is, but i wanted to simplify things here

The book is very good, now I'm finishing the CMS section and I have to ask - since I do these things without framework, It's quite a pain to write even a simple CMS with a security in the first place -> I mean posting SQL with a placeholder value to prepare() it and the bindvalue with the real value and execute() ...and so on...I understand what the code is doing, I also try to write it all by myself after reading it first but I have a feeling that if I have to write all of it from scratch, I think, I would be overwhelmed with it. So I hope it will be a lot easier(smoother) with a framework.

So after finishing the book I'm considering to learn Symfony - do you think it's a good choice? Or do you think I should deepen pure PHP first? I know it's another Q but since you both guys (who recommended me the book) are here...but I will be evaluating original Q.
Ray PaseurCommented:
These two statements are equivalent:
$x = array();
$y = [];

Open in new window

You can add elements to the end of an array with something like this:
$z[] = 'thing 1';
$z[] = 'thing 2';

Open in new window

Symfony is a good choice.  I recommend Laravel.
http://laravel.com/

Here's an example that might help simplify the data retrieval.  There is a lot of code here, but it's mostly just setup for what happens after line 75.  In particular, line 78 gets you all of the rows without any need to write an iterator or copy the data - it's all there in the correct format -- easy!
http://iconoun.com/demo/temp_fajer39.php

<?php // demo/temp_fajer39.php
ini_set('display_errors', TRUE);
error_reporting(E_ALL);
echo '<pre>';


// CREATE AN ARRAY OF NAMES TO USE FOR TEST DATA
$test_names_arrays = [['name' => 'Walter'], ['name' => 'Ray'], ['name' => 'Marco']];


// OPEN A CONNECTION TO THE DATA BASE SERVER AND SELECT THE DB
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";
$db_user = "??";
$db_word = "??";

$dsn = "mysql:host=$db_host;dbname=$db_name";
try {
    $pdo = new PDO($dsn, $db_user, $db_word);
}
catch(PDOException $exc) {
    var_dump($exc);
    trigger_error($exc->getMessage(), E_USER_ERROR);
}
// SET PDO TO TELL US ABOUT WARNINGS OR TO THROW EXCEPTIONS
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );


// CREATING A TABLE FOR OUR TEST DATA
$sql
=
"
CREATE TEMPORARY TABLE my_table
( id    INT         NOT NULL AUTO_INCREMENT PRIMARY KEY
, name  VARCHAR(24) NOT NULL DEFAULT ''
)
"
;

// RUN QUERY TO CREATE THE TABLE
try {
    $pdos = $pdo->query($sql);
}
catch(PDOException $exc) {
    var_dump($exc);
    trigger_error($exc->getMessage(), E_USER_ERROR);
}


// PREPARE THE QUERY TO LOAD THE NAMES ("PREPARE" ONLY NEEDED ONCE)
$sql = "INSERT INTO my_table ( name ) VALUES ( :name )";
try {
    $pdos = $pdo->prepare($sql);
}
catch(PDOException $exc) {
    var_dump($exc);
}


// LOADING OUR DATA INTO THE TABLE
foreach ($test_names_arrays as $person)
{
    // USE THE ARRAY OF KEYWORD => VALUE TO ATTACH name
    try {
        $pdos->execute($person);
    }
    catch(PDOException $exc) {
        var_dump($exc);
        trigger_error($exc->getMessage(), E_USER_ERROR);
    }
}


// QUERY TO RETRIEVE THE ROWS FROM THE DATABASE TABLE
try {
    $pdos = $pdo->query("SELECT id, name FROM my_table");
    $rows = $pdos->fetchAll(PDO::FETCH_ASSOC);
    print_r($rows);
}
catch(PDOException $exc) {
    var_dump($exc);
    trigger_error($exc->getMessage(), E_USER_ERROR);
}

Open in new window

Fajer39Author Commented:
Thank You very much.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.