[PHP] Hyphen to underscore inside forloop

Thor

Honorary Master
Joined
Jun 5, 2014
Messages
44,413
Reaction score
7,522
Location
Bellville
Hello,

Since you cannot redeclare a function in PHP, how would I go about to change the hyphens to underscores in my loop?


PHP:
foreach ($websites as $website)  {
  
    $website_name = $website['name']; //The-New-York-Times
  
    function replaceDashes (&$website_name) {
        $vars = get_object_vars($website_name);
        foreach ($vars as $key => $val) {
            if (strpos($key, "-") !== false) {
                $newKey = str_replace("-", "_", $key);
                $website_name->{$newKey} = $val;
                unset($website_name->{$key});
            }
        }
    }

    $url = "http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=";
    $url .= $website_name;
    $url .= "&format=json&explaintext&redirects&inprop=url&indexpageids";

    $json = file_get_contents($url);
    $data = json_decode($json);

    $pageid = $data->query->pageids[0];
    echo $data->query->pages->$pageid->extract;


}

The above will result in the following error:

Fatal error: Cannot redeclare replaceDashes() (previously declared
 
Oh fck wait.

$item = preg_replace('/\ +/', '-', $item);
 
That wont work has to applied to each site while it loops
regular expressions for the win
I don't understand. You need a new function created for each website you are looping through?
 
I don't understand. You need a new function created for each website you are looping through?

I solved the issue with string replace issue now is how do i use ucwords() on a word like The_new_york_times I need it to be The_New_York_Times
 
I solved the issue with string replace issue now is how do i use ucwords() on a word like The_new_york_times I need it to be The_New_York_Times

I think something like ucwords( str_replace('_',' ',$yourstring)

or

str_replace(' ','_',(ucwords( str_replace('_',' ',$yourstring)))) if it has to remain with underscores

don't do php myself so guessing a bit
 
Last edited:
I think he does not have scoping properly under the belt yet. Try it outside the loop next time Thor.

How would it work outisde the loop? If it has to be applied to the data that gets retrieved by the loop?


PHP:
      $pdo = $conn;
      $sql = "SELECT * FROM websites ";
      $sql .= "ORDER BY views ASC ";
      $sql .= "LIMIT 12";
      $sth = $pdo->prepare($sql);
      $sth->execute();

    $coins = $sth->fetchAll();

Anyway, the string replace did the trick.
 
How would it work outisde the loop? If it has to be applied to the data that gets retrieved by the loop?


PHP:
      $pdo = $conn;
      $sql = "SELECT * FROM websites ";
      $sql .= "ORDER BY views ASC ";
      $sql .= "LIMIT 12";
      $sth = $pdo->prepare($sql);
      $sth->execute();

    $coins = $sth->fetchAll();

Anyway, the string replace did the trick.

You have to correctly utilize function parameters if something is needed that is only scoped within the loop. For a start php is weakly typed, so it does not matter what you pass through, just add more parameters to your function.
 
Last edited:
You have to correctly utilize function parameters if something is needed that is only scoped within the loop. For a start php is weakly typed, so it does not matter what you pass through, just add more parameters to your function.

Your face is weakly typed.
 
How would it work outisde the loop? If it has to be applied to the data that gets retrieved by the loop?

I'm not a php programmer but I suspect you declare the function outside of the loop and then call it from within the loop as in: website_name = replaceDashes($website['name']);
Anyway, as you say string replace works so no need to reinvent the wheel
 
And add a return statement to the function...

Regular expressions are also bit convoluted for your scenario, stick with str_replace as c4c said for simple cases (you don't really need the function you declared anyway). I can't see how regex changed anything for your looping mechanism/function problem?
 
Last edited:
How would it work outisde the loop? If it has to be applied to the data that gets retrieved by the loop?


PHP:
      $pdo = $conn;
      $sql = "SELECT * FROM websites ";
      $sql .= "ORDER BY views ASC ";
      $sql .= "LIMIT 12";
      $sth = $pdo->prepare($sql);
      $sth->execute();

    $coins = $sth->fetchAll();

Anyway, the string replace did the trick.

I'm just curious as to why you're concatenating it across three lines?
If you need to bind variables, use
PHP:
$sth= $pdo->prepare("SELECT * FROM ? ORDER BY ? ASC LIMIT ?");
$sth->bind_param("ssi", "websites", "views", 12);
$sth->execute();

Then you can use the same statement, just bind different variables to adjust for changes (that's if you're using the same statement).
 
I'm just curious as to why you're concatenating it across three lines?
If you need to bind variables, use
PHP:
$sth= $pdo->prepare("SELECT * FROM ? ORDER BY ? ASC LIMIT ?");
$sth->bind_param("ssi", "websites", "views", 12);
$sth->execute();

Then you can use the same statement, just bind different variables to adjust for changes (that's if you're using the same statement).

what he said
 
I would highly recommend against using query parameters for table and field names. It might “work” in this case, but will quickly become an unreadable mess in more complicated queries

I would not let that code be merged into develop.

I would also recommend taking the minor character count hit and using named parameters instead. Again, in simple scenarios it might not be a problem, but it can get become very easy to pass values in the wrong order, or leave them out completely.

Imagine this query:

INSERT INTO ? (?,?,?,?,?,?,?,?) VALUES (?,?,?,?,?,?,?,?)

Named parameters would then make you replace the first 9 with hard coded inline values, and the actual values would be very easy to read what is being set to what

[“id” -> $entity->getId(), etc]//whatever the php array syntax is
 
Last edited:
I would highly recommend against using query parameters for table and field names. It might “work” in this case, but will quickly become an unreadable mess in more complicated queries

Yeah, thought he was using the query in the loop and changing the variables required, on re-read, I realize he's not.
 
Top
Sign up to the MyBroadband newsletter
X