Zero-dependency directed and undirected weighted Graph library for HolyPHP with BFS, DFS, Dijkstra shortest path, topological sort, and cycle detection.
bundled — works offlinezero dependenciesbfsdfs
Quick start
import "graph";
$g = graph_directed();
$g->addEdge("A", "B", 2.0);
$g->addEdge("B", "C", 3.0);
$g->addEdge("A", "C", 10.0);
$res = $g->dijkstra("A", "C");
println("Distance: " . $res["distance"]); // 5
println("Path: " . implode(" -> ", $res["path"])); // A -> B -> C
$order = $g->toposort();
println("Topo: " . implode(", ", $order)); // A, B, C
hasCycle(): bool — Returns true if the graph contains a cycle (supports both directed and undirected graphs).
toposort(): array — Returns a topological ordering of nodes for a directed acyclic graph (DAG).
Error Handling
All invalid operations throw Exception with clear, prefixed messages:
Empty node/edge names: graph: node name cannot be empty / graph: edge endpoints cannot be empty
Missing nodes (neighbors, bfs, dfs, dijkstra): graph: node '<name>' does not exist / graph: start node '<name>' does not exist / graph: target node '<name>' does not exist
Negative weights in Dijkstra: graph: dijkstra does not support negative edge weights (found <w> on edge '<u>' -> '<v>')
Topological sort on undirected graph: graph: toposort is only supported on directed graphs
Topological sort on cyclic graph: graph: cannot perform topological sort on a graph containing a cycle
Examples
01Quick start
Bundled with the compiler — import "graph"; works offline in any file, or add it to a project with hphp install graph.
import "graph";
$g = graph_directed();
$g->addEdge("A", "B", 2.0);
$g->addEdge("B", "C", 3.0);
$g->addEdge("A", "C", 10.0);
$res = $g->dijkstra("A", "C");
println("Distance: " . $res["distance"]); // 5
println("Path: " . implode(" -> ", $res["path"])); // A -> B -> C
$order = $g->toposort();
println("Topo: " . implode(", ", $order)); // A, B, C
Try it
hphp install graph
hphp run main.hphp
Covered by the official test suite in tests/positive/lib_graph.hphp.